VBA: How to make an IF statement on a DateDiff function - vba

In a VBA project i'm working on, I need to count the number of lines where the difference between two dates is inferior to X hours.
My idea was to go through all the lines and check for each line, like this:
Dim count as Integer
if DateDiff("h", date1, date2) < 24 then
count = count + 1
End If
The problem is that I get an incompatibility type error (execution error 13).
Is it possible to make IF statements on a DateDiff function? Or is it maybe possible to make a filter with DateDiff as the condition?
Thanks for the help and sorry for my poor english as it's not my main language!

I have tested it like this without any errors.
Dim date1 As Date
Dim date2 As Date
date1 = "14/10/2015 19:00:00"
date2 = "14/10/2015 16:28:43"
If DateDiff("h", date1, date2) < 24 Then
count = count + 1
End If

The VBA conversion function CDate can apply a little of the overhead you constantly pay for to correct the dates. With that said, it is best to correct the data to begin with and not rely upon error controlled conversion functions.
Dim date1 As Date, date2 As Date, n As Long
date1 = CDate("14/10/2015 19:00:00")
date2 = CDate("14/10/2015 16:28:43")
Debug.Print date1 & " to " & date2
If IsDate(date1) And IsDate(date2) Then
If DateDiff("h", date1, date2) < 24 Then
n = n + 1
End If
'alternate
If date2 - date1 < 1 Then
n = n + 1
End If
End If
Given that 24 hours is a day and a day is 1, simple subtraction should be sufficient for this base comparison.
Your DMY format may cause problems with the EN-US-centric VBA in date conversion. If an ambiguous date string is found (e.g. "11/10/2015 16:28:43") you may find that you are interpreting it as MDY.

Related

Getting all the dates between two selected dates

Good afternoon, I'm new to programming and I'm working with VB.NET.
I need to get the difference between two dates and then list all the intermediate dates in listbox1. I tried the following code but it doesn't work.
Private Sub breaks()
Dim date1 As Date = DateTimePicker1.Value.ToString("dd/MM/yyyy")
Dim date2 As Date = DateTimePicker2.Value.ToString("dd/MM/yyyy")
While date1 <= date2
Dim result = date1
ListBox1.Items.Add(result)
Dim term = 1
date1 = DateTimePicker1.Value.AddDays(term)
End While
End Sub
The function is called within a button. When executed it only shows the sidebars but is blank.
The image shows start date 03/10/2020 and end date 03/16/2020, however the result (listbox) does not return anything.
I expected my result to come:
03/10/2020
03/11/2020
03/12/2020
03/14/2020
03/15/2020
03/16/2020
the interval between them.
Can anyone tell me what's wrong?
You can use some linq for a simple solution
ListBox1.DataSource =
Enumerable.Range(0, 2 + DateTimePicker2.Value.Subtract(DateTimePicker1.Value).Days).
Select(Function(offset) DateTimePicker1.Value.AddDays(offset)).
ToList()
It generates a list of numbers to act as the offset from the initial date, then adds them the specified number of times (different between the dates in days) to create all the dates. No loop required.
Credit to this answer
Edit:
This can also be similarly applied to a DataGridView, but in order to make a single column, we would need to select an anonymous type.
DataGridView1.DataSource =
Enumerable.Range(0, 2 + DateTimePicker2.Value.Subtract(DateTimePicker1.Value).Days).
Select(Function(offset) New With {.Date = DateTimePicker1.Value.AddDays(offset)}).
ToList()
You should avoid using strings for datetimes until they need to be text.
The variable date1 can be used for all the dates, like this:
Dim date1 As Date = DateTimePicker1.Value
Dim date2 As Date = DateTimePicker2.Value
While date1 <= date2
ListBox1.Items.Add(date1.ToString("MM/dd/yyyy"))
Dim term = 1
date1 = date1.AddDays(term)
End While
Also, you should make sure to set Option Strict On as the default for new projects, and set it for the current project.

VBA Get specific differences in hours

I'm having trouble in getting the detailed or specific differences between two dates in minutes. Let's say:
Date Start : 24/7/2015 12:38:00 PM
Date End : 27/7/2015 12:12:00 PM
My code did give the differences between both date but actually does not specific, which means it gives difference of 3 days between both date, but not just I want (Let's say their difference is 68hours 30minutes 56seconds). So, how can I do this?
Here is my code :
Date1 = DateValue(CurrentSheet.Cells(PRow, "U").Value)
Date2 = DateValue(CurrentSheet.Cells(PRow, "S").Value)
FRow = CurrentSheet.UsedRange.Cells(1).Row
lrow = CurrentSheet.UsedRange.Rows(CurrentSheet.UsedRange.Rows.count).Row
For PRow = lrow To 2 Step -1
CurrentSheet.Cells(PRow, "AD").Value = DateDiff("d", Date2, Date1) 'produce days
CurrentSheet.Cells(PRow, "AE").Value = DateDiff("h", Date2, Date1) 'produce hours
CurrentSheet.Cells(PRow, "AF").Value = DateDiff("n", Date2, Date1) 'produce minutes
Next PRow
Currently the answer I got :
3 days,
72hours (3 times 24hours),
1440minutes (24hours times 60minutes).
The reason is that you have used function DateValue that converts a value to date only (time part is removed).
So, those dates:
Date Start : 24/7/2015 12:38:00 PM
Date End : 27/7/2015 12:12:00 PM
after processing them with DateValue function became:
Date Start : 24/7/2015 00:00:00
Date End : 27/7/2015 00:00:00
[EDIT]
You need to convert them to Date type.
You can use VBA built-in function CDate to do that:
Date1 = CDate(CurrentSheet.Cells(PRow, "U").Value)
Date2 = CDate(CurrentSheet.Cells(PRow, "S").Value)
Internally, dates are stored as number of days since Jan-1-1900 (or 1902, in does not really matter). That means 1 day = 1, that also means 1 hour = 1/24.
So if I understand your question correctly, to get the difference in days, hours, minutes between date2 and date1, you could use
daysdiff = DateDiff("d", Date2, Date1)
hoursdiff = INT((Date2-date1-Daysdiff)/24)
'or
hoursdiff = DateDiff("h", Date2-daysdiff, Date1)
minutesdiff = Datediff("n", Date2-daysdiff-hoursdiff/24, Date1)
Sorry, not tested, but you get the idea.
Edit: you should also include #mielk remarks in you changes.
Actually, it's simple! I never thought of this way could produce the answer just like I want! :)
Dim FRow As Long
Dim lrow As Long
Dim PRow As Long
Range("AD1").Value = "Hours Differences"
Dim CurrentSheet As Worksheet
Set CurrentSheet = Excel.ActiveSheet
FRow = CurrentSheet.UsedRange.Cells(1).Row
lrow = CurrentSheet.UsedRange.Rows(CurrentSheet.UsedRange.Rows.count).Row
For PRow = lrow To 2 Step -1
CurrentSheet.Cells(PRow, "AD").Value = (CurrentSheet.Cells(PRow, "U").Value - CurrentSheet.Cells(PRow, "S").Value) * 24
Next PRow
It will produce 71.5666666666511. I was distracted by DATE format. Thanks all for those helps! :D

Excel VBA yearfrac with mins and maxes

I'm trying to find the number of weeks between two dates in Excel VBA (with some min/max functionality in between), was getting Type Mismatch error (Run-time error '13') for the following line:
WeeksWorked = Application.WorksheetFunction.RoundDown _
(52 * Application.WorksheetFunction.YearFrac _
(Application.WorksheetFunction.Max(DOH, DateValue("Jan 1, 2012")), _
DateValue("Dec 31, 2012")), 0)
Anyone have any direction as to what I'm doing wrong, it would be greatly appreciated!
Not sure why do you need to use this in VBA, here is something you can try.
In Excel:
Assuming Start Date is in A1, End Date is in A2, then A3,
=(NETWORKINGDAYS(A1,A2))/5
Now that is in the perspective of business days, thus giving 5 day week. If you need 7 day week with regular days,
=WEEKNUM(A3)-WEEKNUM(A2)
The function WEEKNUM() in the Analysis Toolpack addin calculates the correct week number for a given date, if you are in the U.S. The user defined function below will calculate the correct week number depending on the national language settings on your computer.
If you still need to use VBA try this: (as Tim pointed out DateDiff pretty handy.) Or you can even use Evaluate to trigger WEEKNUM.
Option Explicit
Function numWeeks(startDate As Date, endDate As Date)
numWeeks = DateDiff("ww", startDate, endDate)
End Function
Using Evaluate on WEEKNUM:
Function numWeeks(startDate As Range, endDate As Range)
Dim s As Integer, t As Integer
s = Application.Evaluate("=WEEKNUM(" & startDate.Address & ",1)")
t = Application.Evaluate("=WEEKNUM(" & endDate.Address & ",1)")
numWeeks = t - s
End Function
Reference for Excel VBA DataTime Functions
As suggested in the comments you could just do:
debug.print DateDiff("ww", DateValue("Jan 1, 2012"), DateValue("Dec 31, 2012"))
If for some reason you wanted to roll your own you could truncate the quotient of:
| day1 - day2 |
---------------
7
Example code:
Sub test_numWeeks_fn()
Call numWeeks(DateValue("Jan 1, 2012"), DateValue("Dec 31, 2012"))
End Sub
Function numWeeks(d1 As Date, d2 As Date)
Dim numDays As Long
numDays = Abs(d1 - d2)
numWeeks = Int(numDays / 7)
Debug.Print numWeeks
End Function
Result:
52
Try below code :
Sub example()
Dim dob As Date
dob = #7/31/1986#
Dim todaydt As Date
todaydt = Date
Dim numWeek As Long
numWeek = DateDiff("ww", dob, todaydt) ' Difference in weeks
End Sub

VB DataView.RowFilter and Cast Before Compare

In the following DataView.Rowfilter filter, Request_Date is a smalldatetime:
dv.RowFilter = "Request_Date >= '01/01/2012' and Request_Date <= '12/31/2012'"
The problem with this is that smalldatetime is MM/dd/yyyy hh:mm:ss, but it is compared to a string with the format 'MM/dd/yyyy'. This means that the filter will automatically convert the strings to smalldatetime, so the comparison only shows date/times between 1/1/2012 at 12AM and 12/31/2012 at 12AM. Any rows with dates later in the day on 12/31/2012 will not get picked up by this filter. I know that I can add a day to the end date or concatenate, say, 12:59:59 to the end of the date to pick up the other times in the day, but I was hoping for somthing more elegant, along the lines of the sql equivalent ...CONVERT(smalldatetime, Request_Date, 101) <= '12/31/2012'. Is there any way that I can get a different date format for a DataView field or am I stuck massaging the end date prior to comparison?
FYI, current best option is this:
dv.RowFilter = "Request_Date >= #" & dtpStartDate.DateText & "# and Request_Date <= #" & DateAdd(DateInterval.Day, 1, dtpEndDate.DateValue) & "#"
Thanks for your help!
If you're using at least .NET 3.5, you can use Linq-To-DataSet which is more readable:
DataTable filtered = dv.Table
.AsEnumerable()
.Where(r => r.Field<DateTime>("Request_Date") >= dtpStartDate.Value
&& r.Field<DateTime>("Request_Date") < dtpEndDate.Value.AddDays(1))
.CopyToDataTable();
Add using.System.Linq; and a reference to System.Data.DataSetExtensions.dll.
Edit: I've only just seen that VB.NET is tagged:
Dim filtered = From row In dv.Table
Where row.Field(Of DateTime)("Request_Date") >= dtpStartDate.Value AndAlso _
row.Field(Of DateTime)("Request_Date") < dtpEndDate.Value.AddDays(1)
Dim tblFiltered = filtered.CopyToDataTable()
Instead of using "<= 12/31/2012", just use "< 1/1/2013" - that is the most elegant and gets exactly what you want.

how to compare time in vba

I want to write a macro that compares two times that is available in cells A1 and B1
I tried to use the following code BUT it gave me "type dismatch" at date1 = TimeValue(Range("A1"))
for example, the value at cell A1 like this 11/18/2011 10:11:36 PM
dim date1 as date
dim date2 as date
date1 = TimeValue(Range("A1"))
date1 = TimeValue(Range("B1"))
if date1 > date2 then
'do something
else
'do something else
end if
you need to use Range("A1").Value
Two things:
try changing the value in A1 to 11/10/2011 10:11:36 PM If things
now work you may have a Regional Settings mismatch
you've declared date1 and date2 but are assigning twice to date1 and never
assigning to date2
use application.worksheetfunction.mod( date value, 1 )
You ought to understand that date and time in excel is represented by a serial number, in which 1 equals to a day, and time is repredented by decimals or fractions.
All systems base their date from day zero which us January 1, 1900 = 1, and January 2, 1900 = 2 and so on.
On the excel worksheet you cab retrieve the current date snd time using today(). On vba you use Now instead. Todays date, in "0" or "General" number formatting should show a number that starts with 42..., which represents the number of days since January 1, 1900.
Since there are 24 hours within a day, if you wish to refer to 1 hour or 1:00 AM the fraction or decimal in the serial number is equalent to 1/24. 7:00 PM = 19/24
mod() is a formula or function that will return the remainder of a division. Remember that time is represented by decimals, you do not need the actual whole numbers.
You can use the mod() formula in vba by using "application.worksheetfunction." before any.
When you divide a date and time with 1 using mod() it will return the remainder which is the decimal portion of your date aka the time.
Comparing datevalue("1:00 PM") will not equal CDate("May 8, 2015 1:00 PM")
sub compare_dates()
dim date1 as date
dim date2 as date
dim str as string
str = activesheet.range("A1").value 'str = "11/18/2011 10:11:36 PM"
str = Left(str,Instr(str," ")-1) ' str = "11/18/2011"
date1 = str ' assign it to date1
str = activesheet.range("B1").value ' in the same way b1 cell value
str = left(str,instr(str," ")-1)
date2 = str
if date1 > date2 then
' do something
end if
end sub
Can't it be done by simply using .Text instead of .Value?
Dim date1 As Date
Dim date2 As Date
Dim date3 As Date
date1 = TimeValue(Range("A1").Text)
date2 = TimeValue(Range("B1").Text)
date3 = TimeValue(Range("C1").Text)
If date3 >= date1 And date3 <= date2 Then
'Yes!
Else
'No!
End If