Column A is StartDate
Column B is EndDate
When I run the Macro it returns the answer 1 for all my dates as I am adding 1 to my DateDiff, then DateDiff must be 0.
What is wrong with my DateDiff ?
Sub CalculateDays()
Dim LastRow As Long
Dim StartDate As Date
Dim EndDate As Date
Dim Days As Single
With Worksheets("Sheet1")
'Determine last Row in Column A
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
'Calculate Difference between Start Date And End Date in Days
For i = 2 To LastRow
StartDate = .Cells(i, 1)
EndDate = .Cells(i, 2)
Days = DateDiff("d", StartDate, EndDate)
.Cells(i, 3) = Days + 1
Days = 0
Next i
End With
End Sub
Sample data:
Start Date | End Date
=========================
13-Feb-17 | 28-Feb-17
14-Feb-17 | 28-Feb-17
02-Mar-17 | 04-Mar-17
13-Feb-17 | 15-Feb-17
13-Feb-17 | 13-Feb-17
15-Jan-17 | 15-Feb-17
01-Feb-17 | 12-Feb-17
Your code actually runs fine for me - but I am sure that the values in columns A and B are actually dates. If you are not sure about this then use the CDate function to ensure that the value in the cells is converted to a date before passing to the DateDiff function e.g.
StartDate = CDate(.Cells(i, 1).Value)
Your code with this added in:
Option Explicit
Sub CalculateDays()
Dim LastRow As Long
Dim StartDate As Date
Dim EndDate As Date
Dim Days As Single
Dim i As Long
With Worksheets("Sheet1")
'Determine last Row in Column A
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
'Calculate Difference between Start Date And End Date in Days
For i = 2 To LastRow
StartDate = CDate(.Cells(i, 1).Value)
EndDate = CDate(.Cells(i, 2).Value)
Days = DateDiff("d", StartDate, EndDate)
.Cells(i, 3) = Days + 1
Days = 0
Next i
End With
End Sub
Edit
I just read this where it states a problem with South African date formats:
.. my region was "English (South Africa)") and I had the date separator as "/", however Excel kept changing this to a "-". ...
So maybe it's worth checking on your regional settings and maybe reformat your dates as dd/mmm/yyyy instead of dd-mmm-yyyy and checking the output.
Maybe the CDATE function will not be required after all (as I mentioned your code ran fine for me in an Australian English regional setting context).
Alternatively, instead of a function just write a formula:
=ROUND(B2-A2+1,0)
why do you need datediff function. to get the days difference use
days=enddays - startdate
your code is working fine in excel 2016 in widows. As mentioned by #RobinMackenzie you have some problem with regional date settings.
Related
I need to make a form in Excel that asks for a start and end date. Then, I need to write a VBA script that writes out each day within that range in the first blank cell in column A.
So, for example, if it was given:
Start Date: 1/5/2017
End Date: 1/9/2017
The Result would be:
1/5/2017
1/6/2017
1/7/2017
1/8/2017
1/9/2017
Then if it is run again with a new date range, the dates would append to the bottom of the list. This is just a short example, in practice the date ranges would be much larger and consist of several months.
I'm not really sure where to begin with this, so any help would be greatly appreciated!
As #Ron Rosenfeld mentioned, a date in VBA is only a number that can be increased or decreased with simple numeric operations. This code should do exactly what you want:
Dim startDate As Date
Dim endDate As Date
startDate = DateSerial(2017, 1, 1)
endDate = DateSerial(2017, 1, 23)
Dim sheet As Worksheet
Set sheet = Worksheets("Table1")
Dim i As Integer
i = 1
While startDate <= endDate
sheet.Cells(i, 1) = startDate
startDate = startDate + 1
i = i + 1
Wend
I have seen how to loop through weeks of a year, w1301,w1302,w1303, I can get the week number if i loop through + on week number but I believe there is a way to directly loop weekly with vba, i hope at least.
DateSerial(Year(Now), Month(Now), Day(Now)) To DateSerial(2013, 3, 1)
StartDate = #1/1/2013#
EndDate = #12/31/2013#
For DateLooper = StartDate To EndDate
I got the function for a week number from date
Public Function IsoWeekNumber(d1 As Date) As Integer
Attributed to Daniel Maher
Dim d2 As Long
d2 = DateSerial(Year(d1 - WeekDay(d1 - 1) + 4), 1, 3)
IsoWeekNumber = Int((d1 - d2 + WeekDay(d2) + 5) / 7)
End Function
You could just use the DateAdd function
For i = 1 To 52
Debug.Print DateAdd("ww", i, Now())
Next i
A day has an integer value of 1, so you could iterate by week like this:
startDate = #1/1/2013#
endDate = #12/31/2013#
For d = startDate To endDate Step 7
'do stuff
Next
The week number can be determined with the DatePart function, e.g.:
WScript.Echo DatePart("ww", Now)
This will work in both vbscript and vba.
I tried this solution and it seems to work, am not 100% sure of how it handles the 28,30,31 days of different months but i trust vba. i know am making a mistake probably :))
currentDate = "2013-01-02" ' coz i wanted to start on a wednesday
for week = 1 to 52
debug.print currentDate
currentDate = DateAdd("ww",1,currentDate)
next week
What I am trying to do is check column AJ for each date that occurs during a year determined by variable "Año". For the dates that are I would like to see how far into the year they are (that is how many days after the first January each date occurs); this is the part that is giving me the error (indicated in my code). What I need is a function to give how many days into the year a date occurs or a better way of writing that line of code.
For Each cl In Workbooks(WbkA).Worksheets("Sheet1").Range("AJ2:AJ1000")
If (cl.Value - ("01/01/" & Año)) > 0 And (cl.Value - ("01/01/" & Año)) < 366 Then 'if it´s in this year
ValueA = ValueA + (cl.Value * ((cl.Offset(0, -13).Value - ("01/01/" & Año)) / 365)) ' this part is giving me the error
End If
End If
Next cl
You are complicating things too much. DateDiff can perform the calculations you want:
Dim iniDate As Date, curDate As Date
Dim ValueA As Integer, Año As Integer
Año = 2010
iniDate = Format(CDate("01/01/" & Año), "MM/dd/yyyy") 'You can change the Format
curDate = Format(CDate("01/05/" & Año), "MM/dd/yyyy")
ValueA = DateDiff("d", iniDate, curDate) 'RESULT -> 4
Dates are stored as the number of days since 1/1/1900, so you can just subtract two dates to get the number of days.
Dim lAno As Long
Dim rCell As Range
Dim dValueA As Double
lAno = 2010
For Each rCell In Sheet1.Range("AJ2:AJ100").Cells
If Year(rCell.Value) = lAno Then 'if it's in the year
'+= some value * the number of days
dValueA = dValueA + (rCell.Offset(0, -13).Value * (rCell.Value - DateSerial(lAno, 1, 1)))
End If
Next rCell
I need to summarize some info depending on the date. I mean, I need to sum some info if the date correspondig to that info is within an interval.
Is there anyway to do it?
I have seen "DATEDIFF", but what I need would be something like:
'If the data evaluted is whitin the next interval sum the value.
Hope you understood my question.
Thanks in advance.
EDITED: I added a pic to make it more understandable
This will do it. I don't know where you want to use total, so now you just get a messagebox.
Sub SumBetweenTwoDates()
Dim total As Integer
total = 0
Dim firstDate As Date, secondDate As Date
firstDate = DateValue("20/11/2012")
secondDate = DateValue("20/12/2012")
For i = 1 To 5
If Range("A" & i).Value >= firstDate And Range("A" & i).Value <= secondDate Then
total = Range("B" & i).Value + total
End If
Next i
MsgBox total
End Sub
Use one formula in the cell you want the sum in:
Assuming the value is in A1:A100 and the dates are in B1:B100
=SUMPRODUCT((B1:B100>=DATEVALUE("1/1/2004"))*(B1:B100<=DATEVALUE("31/1/2004")),A1:A100)
will return the sum of the values fro January 2004
I have a table with a large amount of information, how do i select just the last months worth? (ie just the last 31 cells in the column?)
The data is in the form
date1 numbers
date2 numbers
. .
. .
. .
daten numbers
where date1 is dd/mm/ccyy
cheers
Ideally there would be a column that has the date in it. Then you could do an advanced filter to filter on the date range that you require. Selecting the last 31 days will not always select just one month. It may select up to 3 days from the previous month as well.
Public Sub selectLastMonth()
Dim ws As Worksheet
Dim dStart As Date, dEnd As Date
Set ws = ActiveSheet
ws.Range("A:B").Sort key1:=ws.Range("A2"), header:=xlYes
dEnd = ws.Range("A1").End(xlDown).Value
dStart = DateSerial(DatePart("yyyy", dEnd), DatePart("m", dEnd), 1)
ws.Range("A:B").AutoFilter field:=1, Criteria1:=">=" & dStart, Operator:=xlAnd, Criteria2:="<=" & dEnd
Set ws = Nothing
End Sub
use
LastRow = Sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row
then you can get the range from LastRow-31 to LastRow
if you have the date as specified then move the start point forward until the date value = date(if(now.month=1,now.year-1,now.year), if(now.month=1,12,now.month-1), now.day)