How to make a spreadsheet formula execute every day - sql

I have the following formula which fetches data from the same day from table UniqueLast:
=IFERROR(QUERY(UniqueLast!$A$3:X;"select * where dateDiff(A, now())=0"))
It runs correctly but sometimes the table where this formula is executed keeps the result from the previuos day which is already old. How can I make a regulation for running the formula in 00:00?

Create a macro function and include the above expression. Use VBExpress and create a script (.exe) to open the spreadsheet and run the macro. Add it in the Windows scheduled tasks.
Function to call in Macro
Function getNextRunTime() As Date
Dim curDate As Date
Dim curTime As Date
Dim chkTime As Date
Dim runTime As Date
curDate = Date
curTime = TimeValue(Now)
runTime = curDate + TimeValue("15:59:00")
chkTime = curDate + curTime
If chkTime > runTime Then 'schedule for next day'
runTime = DateAdd("d", 1, runTime)
End If
getNextRunTime = runTime
End Function

The SQL statement parameter of the QUERY function should be a single value of type TEXT. NOW() it not valid Google Query Language function. Google Sheets magnes dates on the background as numbers with a different EPOCH date so we should convert it to a date with the proper format. Try
=QUERY(
UniqueLast!$A$3:X,
"select * where dateDiff(A, date """&TEXT(now(),"yyyy-mm-dd")&""")=0"
)
Removed IFERROR in order to make it easy to check if change proposed works with the OP data. You could add it later once you are sure that it does.

Related

VBA Double to Time

I have a VBA user form which when I press save after input data it writes to a spread sheet and set my time and date to Now() that is being written to a spread sheet where I split the now() value into time and date, when I read it back I get the date but my time in decimal format I would like to convert that decimal number back to time what is the formula for that thank you in advance my decimal number is something like '0.12425576899' so far I found this but it converts that to '00:the minutes on the double:00' here is the code
Public Function FromDecimalTime(ByVal t As Double) As Date
FromDecimalTime = TimeSerial(0, Fix(t), (t - Fix(t)) * 60)
End Function
The following will convert the Double into the Date Format. In order to only show the time portion of the date format, use the Format function:
Sub trythis()
Dim t As Double
t = Now()
Debug.Print CDate(t)
Debug.Print Format(t, "hh:mm:ss")
End Sub

changing date fromat from mm/dd/yyyy to dd/mm/yyyy VBA

So I know this question has been asked a couple of times over, but I believe my situation is a bit different (happy to be proven wrong of course!)
Here is the data flow: a user types a date in a date in a form. They then click a button. My macro then takes that date, runs it through the following function:
Function AddWeekDays(StartDate As Long, Days As Long) As Date
Dim i As Long
Dim d As Date
d = StartDate
i = 0
While i < Days
d = DateSerial(Year(d), Month(d), Day(d) + 1)
If Weekday(d, vbMonday) < 6 Then
i = i + 1
End If
Wend
AddWeekDays = d
End Function
Then it formats the date to change it from mm/dd/yyyy to dd/mm/yyyy in the following way:
Dim deadline As Date
Dim deadline_formatted As Date
Dim DateReceived As String
Dim DateConverted As Date
DateReceived = txt_DateReceived.Text
DateConverted = Format(DateReceived, "dd/mm/yyyy")
deadline = AddWeekDays(DateValue((CStr(DateConverted))), 9)
deadline_formatted = Format(deadline, "dd/mm/yyyy")
However, the deadline_formatted value is still coming out in the mm/dd/yyyy format.
As an example, when a user enters 01/05/2017 the program should return deadline_formatted = 12/05/2017, but it returns deadline_formatted = 05/12/2017
I have tried changing the variable type to string to see if that made a difference (it didn't), and have tried directly converting the deadline variable to the required format by using the following code:
deadline = Format(AddWeekDays(DateValue((CStr(DateConverted))), 9),"dd/mm/yyyy")
which still returns the incorrect format.
Can anybody out there suggest either:
How to fix the formatting issue to get the deadline_formatted into the format dd/mm/yyyy
OR
suggest a "workaround" to flip the "dd" with the "mm" (not ideal obviously, but if it works, it works!)
Thanks for any advice!
The best way to solve this issue is to actually change your computer's default date/time format to match the method used by the users. (In comments it is stated that the users are Australians but your company is US-based, so the default is probably currently set to be the USA's "mm/dd/yyyy" format.)
By ensuring that the computers date/time format is correct, it will allow you to process a date as a Date, and it can be stored in Excel cells as a Date, which then allows any of the Australian users to see it displayed as "dd/mm/yyyy" format while a USA-based colleague would see it displayed as "mm/dd/yyyy".
There is a financial risk to your company caused by forcing users to interact with software using an unfamiliar date system, as accidental entering of dates in the wrong formats can lead to major errors downstream, so it is in the company's best interest to allow you to change the settings to be relevant to the users.
It is not directly related to your problem, however I believe it might fix your issues. The manual calculation of adding week days might be the problem here.
There is a built in function to add workdays. You can include/exclude weekends/holidays. The following code replaces your above mentioned code.
Sub AddWeekDays()
Dim deadline As Date, deadline_formatted As Date
deadline = txt_DateReceived.Value
deadline_formatted = Format(Application.WorksheetFunction.WorkDay(deadline, 9), "dd/mm/yyyy")
'debug.print deadline_formatted
End Sub
the result to be String.
Dim deadline As Date
Dim deadline_formatted As String '<~~ change string
Dim DateReceived As String
Dim DateConverted As Date
txt_DateReceived = "01/05/2017"
DateReceived = txt_DateReceived
DateConverted = Format(DateReceived, "dd/mm/yyyy")
'deadline = AddWeekDays(DateValue((CStr(DateConverted))), 9)
deadline = AddWeekDays(CLng(DateConverted), 9) '<~~ change Long
deadline_formatted = Format(deadline, "dd/mm/yyyy")
I wouldn't bother about the regional settings. Instead, make sure that all dates are captured as Date() or Now() values (42123 or 42123.5555). On the output side such values can be presented in any format you wish.
To ensure that dates are entered correctly my preferred way is to use a date picker. If that can't be done make no rules for entering the date at all, working on the presumption that each user will know how to enter a date on his/her machine. Add a date check, like ISDATE(), which will catch some input errors but not all. You don't need to catch all. You only need to teach users how to input dates on their respective PCs.
With this line you don't need anything else.
Range("E:E").TextToColumns FieldInfo:=Array(0, xlDMYFormat)
'1.2.2019 -> 01/02/2019
'2,3,2019 -> 02/03/2019
'3-4-2019 -> 03/04/2019
'4*5*2019 -> 04/05/2019
'5_-6-*2019 -> 05/06/2019
'and so on
Of course you can change the format with
xlMDYFormat

How to convert VBA Now() into seconds to determine total program runtime

I'm working on a problem where I need to determine the total time my program takes to execute. First line of code needs to write the current "Start time" and last lines of code need to write the current "End time". Then I'm subtracting "Start time" - "End Time" = Total Time.
I'm confused how I would use the FORMAT() function within VBA on the value of C2 to convert into seconds? Is there an other function that would work better than FORMAT? Basically I'm confused about Excel's Date Serial values and what they represent.
Code is below
EDIT: Thanks for the responses everyone. Both answers below work for what I'm trying to do.
sub ExecutionTime()
Worksheets("Table").Range("A2").Value = Now()
'All my executable code goes here. It's a relatively small program compiling a table so it
runs very quick.
Worksheets("Table").Range("B2").Value = Now()
Worksheets("Table").Range("C2").Value = Worksheets("Table").Range("A2").Value - Worksheets("Table").Range("B2").Value
end Sub
Do not use a Date data member or the Now method to analyze run time of your program. Instead, the Timer function is the most appropriate solution as it returns a Single representing seconds. It will require no type conversion and yields a more accurate result than an integer amount of seconds.
Using LimaNightHawk's answer as a template as you should be storing these in local variables instead of writing directly to the worksheet.
Dim startTime as Single
startTime = Timer()
' Do stuff
Dim endTime as Single
endTime = Timer()
Dim runTime as Single
runTime = endTime - startTime
Results should be written at the end of the routine.
With Worksheets("Table")
.Range("A2").Value = startTime
.Range("B2").Value = endTime
.Range("C2").Value = runTime
End With
Documentation on the timer function
In the first line of your program get the date (no need to format):
Dim startTime as Date
startTime = Now()
At the end of your program, get the date again:
Dim endTime as Date
endTime = Now()
Then use the DateDiff
Dim timeInSeconds as long
timeInSeconds = DateDiff("s", startTime, endTime)
DateDiff() is what you are looking for. The "s" defines that you are looking for the difference in seconds.
Worksheets("Table").Range("C2").Value = DateDiff("s", Worksheets("Table").Range("A2").Value, Worksheets("Table").Range("B2").Value)
EDIT: http://www.likeoffice.com/28057/excel-date to learn more about working with dates and times in Excel VBA. It is important to understand that dates work differently within the context of VBA, and have their own unique set of syntax functions for manipulating.
2nd EDIT: A cleaner version of this would be:
StartDateTime = Now()
'Run Code
Worksheets("Table").Range("C2").Value = DateDiff("s", StartDateTime, Now())
There's a few ways you can use VBA to format cells / variables.
In no particular order, firstly you can format ranges with the NumberFormat property which can be applied like so:
Worksheets("Table").Range("C2").Value = Now()
Worksheets("Table").Range("C2").NumberFormat = "ss"
The other way is that you could format Now() using the Format() function:
Worksheets("Table").Range("C2").Value = Format(Now(), "ss")
See the documentation from Microsoft to implement different formats:
NumberFormat: http://msdn.microsoft.com/en-us/library/office/ff196401%28v=office.15%29.aspx
Format: http://msdn.microsoft.com/en-us/library/office/gg251755%28v=office.15%29.aspx
How i generally go about bragging my process time to user
Sub Process()
Dim startTime as Date
Dim endTime as Date
startTime = Now
'Logic for what your process must do
endTime = Now
MsgBox "Process completed in : " & Format(endTime - startTime, "hh:mm:ss")
End Sub

How to compare dateformat rather than using of time

How can I compare the last characters using of month, day, and year or the completedate rather than using datetime, Example case is Textbox3 is greater than textbox9 because Textbox3 day = 26 and textbox9 day = 25.
Mycode:
'in my case I have 2 Textbox.
'Date format: hh.mm MM/DD/YYYY
'Textbox3= 02.02 03/26/2014
'TextBox9= 21.01 03/25/2014
If Val(Strings.Left(TextBox9.Text.Trim, 5)) < Val(Strings.Left(Textbox3 .Text.Trim, 5))Then
TimeError.ShowDialog()
End If
Really, the fastest, most reliable, and most effective way to do this is to parse the values into a DateTime. And taking a step back from there, the fastest, most effective way to get a date time from a textbox is to use a DateTimePicker control.
But if that's not an option, we can build on the code I gave you last time:
Dim temp1() As String = Textbox3.Text.Trim().Split(" .".ToCharArray())
Dim temp2() As String = Textbox9.Text.Trim().Split(" .".ToCharArray())
If DateTime.Parse(temp2(2)) < DateTime.Parse(temp1(2)) Then
TimeError.ShowDialog()
End If
I'll add that you probably want to also have code to compare the time values in the case where the date portions are equal. Given this as a starting point, you should be able to write that code on your own.
in vb.net you can comopare dates like this:
dim date1 as date = cdate(Textbox1.text)
dim date2 as date = Date.now()
if date1.date=date2.date then ....
and months like this
if date1.month=date2.month then ...

convert date in excel from dd-mm-yyyy to dd/mm/yyyy format and to check whether a date is valid or not

I'm having a hard time in converting the date from dd-mm-yyyy format to dd/mm/yyyy format.
For Example,
When i enter a date in excel as 25/02/2012 (dd/mm/yyyy), after entering the date if go in the next line it converts the date in the 25-02-2012 (dd-mm-yyyy) format.
what i want to do is that when i enter the date in (dd/mm/yyyy) format in excel it should keep it as it is and should not change it back to (dd-mm-yyyy) format when i go the next cell.
when i enter my date as the current system date my code gives me an error, i am having trouble validating the date i.e. is the date entered is a valid date or not
Sub valid_date()
' ---------------------------------------------------------------------
' Final Code - Trial
' ---------------------------------------------------------------------
Dim d1 As Variant
Dim IssueDate As Variant
Dim str As Variant
d1 = Worksheets("Sheet1").Cells(6, 1).value
MsgBox " The Issue Date format is " & d1
sysdate = Date
MsgBox "System Date is " & sysdate
If IsDateValid(d1) Then ' if date is in dd/mm/yyyy format then print this
If (d1 > sysdate) Then
MsgBox "Invalid date"
End If
End If
End Sub
Function IsDateValid(pdate) As Boolean
IsDateValid = False
Set RegExp = CreateObject("VBScript.RegExp")
' it only matches whether date is in dd/mm/yyyy format or not
'
' [1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1] ---> it allows the DATE from 01 to 31
' [1-9]|0[1-9]|1[0-2] ---> it allows the MONTH from 01 to 12
' 1[9][0-9][0-9]|2[0][0-9][0-9] ---> it allows the YEAR from 1900 to 2099
'
' below is the regular expression for checking the date in dd/mm/yyyy format
RegExp.Pattern = "^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])[/]([1-9]|0[1-9]|1[0-2])[/](1[9][0-9][0-9]|2[0][0-9][0-9])$"
' check whether the date is in dd/mm/yyyy format or not....
tempdate = RegExp.Test(pdate)
If tempdate Then ' if tempdate is in dd/mm/yyyy format than proceed further
'If isdate(tempdate) Then ' if date is a valid date then proceed further
If isdate(pdate) Then
IsDateValid = True
Else
IsDateValid = False
End If
Else
IsDateValid = False
End If
End Function
i'm using the above mentioned code by using a regular expression to check whether the date is in dd/mm/yyyy format or not
but the problem which i'm facing is that it takes the date in excel as dd-mm-yyyy format whenever i enter the date in dd/mm/yyyy format.
i have updated my code a bit,
i also need one more help when i enter my date as the current system date it gives me error
for example,
when i enter my date as 09/09/2012 (suppose this your current system date) and when i check this date using IsDate method, it gives me an error
i have again edited my code,
Can anyone please help me on this
You don't need VBA/RegEx. Select the cells/columns where you input dates and create a Custom number format: dd/mm/yyyy. Now no matter how you type in a valid date (05-05-2000, 3-1-2010, 14/6-1990, etc.), it should be formatted as dd/mm/yyyy.
And, as Olle points out, you should use the Date object rather than Variant if you are going to be manipulating dates in VBA. This way you're working with the serial number and not a string with potential formatting issues.
First, I suggest you check the regional settings for dates on your computer. If you set it to use the "dd/mm/yyyy" format it will be used by Excel as well and hopefully remove the need for any RegEx VBA-code.
Second, if you do need to use VBA to reformat dates, I strongly suggest you use the Date data type instead of Variants. I also advise you to use Option Explicit at the top of your code and explicitly declare any variables in order to minimize typos and produce better quality code.
Third, I've looked through your code some more and it seems it will never work:
1. Because it is never declared, tempdate is a Variant
2. You assign tempdate to be a boolean, from the result of RegExp.Test(pdate)
3. So when you check IsDate(tempdate) it will always be false, since a boolean can never be a Date.
Again, if you use the Date data type, you can skip the RegEx... :)
I use Adobe online PDF to Excel and dates display correctly as MM/DD/YYYY but when extracting month (=Month()) it returns the DD portion. It is being interpreted as DD/MM/YYYY. I saved the file as a .csv closed and restarted excel and opened the .csv file and the dates were correct MM/DD/YYYY.