I use Excel 2013.
When I subtract two dates in excel "1.11.2019" and "1.10.2019" I get the result 31 as you should.
But when I do the same thing in VBA I get 10000. So it sees them as regular numbers "1112019" and "1102019". How can I get the same result in VBA too?
Use DateDiff() function with d interval to get days difference between two date. Try like below.
Sub DateSubstract()
MsgBox DateDiff("d", Range("B1"), Range("A1"))
End Sub
You may have to format the string into a Date format
Dim diff As Long
Dim strDate1, strDate2 As String
Dim fDate1, FDate2 As Date
Set sh = ThisWorkbook.Sheets("myDate")
' convert in string with 8 caracters
strDate1 = Right("0" & sh.Range("A1").Value, 8)
strDate2 = Right("0" & sh.Range("B1").Value, 8)
'format Year, month, day
fDate1 = DateSerial(Right(strDate1, 4), Mid(strDate1, 3, 2), Left(strDate1, 2))
fDate2 = DateSerial(Right(strDate2, 4), Mid(strDate2, 3, 2), Left(strDate2, 2))
diff = DateDiff("d", fDate2, fDate1)
Debug.Print ("difference :" & diff)
Related
I use a macro to load an Excel file, pull data, and paste it into a log file. Each of the source Excel files are named by the sample date time it was created.
For instance, a sample created November 25th, 2021 at 3:30 PM would have the file name "11-25-21 1530". I want to pull the file name, assign it to a variable, and format that string into the date time format recognized by Excel for plotting (11/25/21 15:30). I cannot change the file names to include the "/" or ":" since these are not valid in file names.
I have something similar using a userform for time only where it autoformats into a 24hr time variable:
Private Sub TextBox2_AfterUpdate()
'Input would be HHMM or HMM
Dim a As String
a = Len(Me.TextBox2)
If a <= 2 Then 'This is for cases with H or HH
On Error Resume Next
Me.TextBox2 = Left(Me.TextBox2, a) & ":" & 0
ElseIf a = 3 Then
Me.TextBox2 = Left(Me.TextBox2, 1) & ":" & Right(Me.TextBox2, 2) 'This is for cases with HMM
Else
If Me.TextBox2.Value >= 2400 Then
MsgBox ("Incorrect Value")
Call CommandButton1_Click
Else
Me.TextBox2 = Left(Me.TextBox2, 2) & ":" & Right(Me.TextBox2, 2) 'This is for cases with HHMM
End If
End If
Me.TextBox2 = Format(Me.TextBox2, "HH:MM")
End Sub
How do I take the file name and split it into a date and then a time, format both to the proper Excel date time format, then combine them again for MM/DD/YY HH:MM output to log the results?
Use simple string handling to split the name into it's pieces. Then use DateSerial and TimeSerial to create a real Date out if it.
Once that is done, you can do whatever you want with the Date. I don't understand your request "into the date time format recognized by excel for plotting (11/25/21 15:30)", I do know that my Excel will have a hard time to understand 11/25/21 correctly (I am not located in the US...). When you write the date into a cell, write it as date and format the cell. If you need it in your code as string, use the Format-command.
The following function will split a filename, just note that there is no error handling or plausability test.
Function FilenameToDate(filename As String) As Date
Dim fileYear As Long, fileMonth As Long, fileDay As Long, fileHour As Long, fileMinute As Long
fileDay = Val(Mid(filename, 4, 2))
fileMonth = Val(Mid(filename, 1, 2))
fileYear = Val(Mid(filename, 7, 2))
fileHour = Val(Mid(filename, 10, 2))
fileMinute = Val(Mid(filename, 13, 2))
FilenameToDate = DateSerial(fileYear, fileMonth, fileDay) + TimeSerial(fileHour, fileMinute, 0)
End Function
I have a program that is supposed to read the date from a cell. In that cell, I have given it the value of =NOW() just by typing it into the cell outside of VBA. The cell is formatted as a date and the format is: dd-month (for example; 28-Jan). When VBA reads the cell, it reads it as mm/dd/yyy 00:00:00 AM/PM. Is there a way to make my code read the month from the format I set? A section of my code is below:
dashpos = InStr(1, ThisWorkbook.Worksheets("Main").Cells(2, 15), "-")
curmonth = Right(ThisWorkbook.Worksheets("Main").Cells(2, 15).Value, dashpos + 1)
The cell containing the date is Cell(2,15). I then go on to use the three letters on the month to determine the following month using a Select Case curmonth.
If your format is mm/dd/yyy 00:00:00 AM/PM in the worksheet, then the month will always have two digits. Therefor:
curmonth = CLng(Left(ThisWorkbook.Worksheets("Main").Cells(2, 15).Text, 2))
Sub testDateExtraction()
'Next day in the format you use in the sheet (no matter, in fact...):
Debug.Print Format(ThisWorkbook.Worksheets("Main").Cells(2, 15).Value + 1, "dd-mmm")
'Next month
Debug.Print MonthName(Month(ThisWorkbook.Worksheets("Main").Cells(2, 15).Value) + 1, True)
'If you insists to use the string type data:
Dim strDate As String, strMonth As String
strDate = CStr(Format(ThisWorkbook.Worksheets("Main").Cells(2, 15).Value + 1, "dd-mmm"))
strMonth = Right(strDate, 3)
Debug.Print MonthName(Month(DateValue(Day(Date) & "-" & strMonth & "-2020")) + 1, True)
End Sub
I then go on to use the three letters on the month to determine the following month
If you want to determine the next month, you can just use DateAdd and Month. The cell format is irrelevant.
The following returns the month number:
Month(DateAdd("m", 1, Cells(2,15)))
If you want it as a three letter string, for some reason, then
Format(DateAdd("m", 1, Cells(2,15)), "mmm")
So I have cells containing strings of date, such as:
14/04/2019 10:13:18 AM
how can I convert it to DateTime using vba?
I've tried using .NumberFormat but some of the cells got converted and some didn't:
My code is
Sub ConvertToDateTime()
With Range("Data[Modified On]")
.NumberFormat = "dd/mm/yyyy hh:mm:ss AM/PM"
.Value = .Value
End With
End Sub
And how do I insert converted value to a new column?
I've created a new column with:
Dim Table As ListObject
Dim newColNum As Integer
Set Table = ActiveSheet.ListObjects("Data")
Table.ListColumns.Add.Name = "New Header"
Can I do it without looping?
Some of the cell do got converted but some don't
That's because the date format on your PC is different than the data (it is mm/dd/yyyy while the data is in "dd/mm/yyyy")
This can't be fixed without looping. (as far as I know)
To fix that, you might need to do something like this:
Sub ConvertToDateTime()
Dim Cell As Range, h As Long, c As Long
Range("Data[New Header]").NumberFormat = "dd/mm/yyyy hh:mm:ss AM/PM"
c = Range("Data[New Header]").Column
For Each Cell In Range("Data[Modified On]")
If Right(Cell.Value, 2) = "PM" Then h = 12 Else h = 0
Cells(Cell.Row, c).Value = DateSerial(Mid(Cell.Value, 7, 4), Mid(Cell.Value, 4, 2), Left(Cell.Value, 2)) + _
TimeSerial(Mid(Cell.Value, 12, 2) + h, Mid(Cell.Value, 15, 2), Mid(Cell.Value, 18, 2))
Next
End Sub
I am processing a .txt file in VBA.
Amongst other tasks, I need to read in a string representing a date and display the actual date in Excel.
A date string in the .txt file looks like "190223"
This represents 23/02/2019
My challenge is to get this done.
What I have done so far is:
' ... loop
With ActiveWorkbook.Worksheets(1)
' Other statements here
' Event date time
.Range("N" & i).Value = StrReverse(Mid(.Range(keyword.Offset(0, 4).Address), 1, 2) & _
"/" & Mid(.Range(keyword.Offset(0, 4).Address), 3, 2) & _
"/" & Mid(.Range(keyword.Offset(0, 4).Address), 5, 2))
End With
But I get the undesired output:
32/20/91 ' For a date string 190223 the desired output should be 23/02/19
Any help would be much appreciated.
Thanks in advance.
Convert it into a real date
You must extract year, month and day of that string and then convert this into a real date.
Then you can format the date to what ever date format you like. The value that is saved in the cell is then a real date value (not a string!) so you can calculate with it.
I highly recommend to read How Dates Work in Excel – The Calendar System Explained + Video to understand the background and why real dates are so important.
Here is an example:
Option Explicit
Public Sub ConvertDateExample()
Const InputStr As String = "190223"
Dim InputYear As Integer
Dim InputMonth As Integer
Dim InputDay As Integer
'extract year, month and day
InputYear = Left(InputStr, 2)
InputMonth = Mid(InputStr, 3, 2)
InputDay = Right(InputStr, 2)
'put it together to a real date
Dim RealDate As Date
RealDate = DateSerial(InputYear, InputMonth, InputDay)
'write the date into a cell
Range("A1").Value = RealDate
'format that cell to your desired format
Range("A1").NumberFormat = "dd/mm/yyyy"
End Sub
I have an 8 digit number that tells me the date, YYYYMMDD. How can I convert this number into a date that Excel will recognize as a date.
Let's assume cell A1 has 20120229 in it...what do I do?
Since you tagged this question VBA, I assume you want an answer in VBA, so here you go:
Dim l As Long
Dim s As String
Dim d As Date
l = Range("A1").Value ' 20120229
' convert it to a string
s = CStr(l)
' can now use string functions to parse it
d = DateSerial(CInt(Left(s, 4)), CInt(Mid(s, 5, 2)), CInt(Right(s, 2)))
' d is now 29 Feb 2012
' write it back to the sheet
Range("A2").Value = d
Use this formula: =DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2)) where A1 is the cell coordinate.
I like being able to select text in excel and call a macro to do the work.
Sub YYYYMMDDToDate()
Dim c As Range
For Each c In Selection.Cells
c.Value = DateSerial(Left(c.Value, 4), Mid(c.Value, 5, 2), Right(c.Value, 2))
'Following line added only to enforce the format.
c.NumberFormat = "mm/dd/yyyy"
Next
End Sub