VBA: How to get date as a string yyyy-mm-dd - excel

I am trying to get the Date as a string formatted yyyy-mm-dd.
I have tried various things with strange results:
Dim mydate As String
mydate = Date
mydate = Year(Date)
mydate = Month(Date)
mydate = Day(Date)
The first one gives 11/02/ without the year.
I can try to concatenate the data but:
The second gives the year OK
However the third gives month as 2 instead of 02
Similar for fourth.
Any clarification or an example would be very welcome.

Use the Format function from the VBA.Strings built-in module:
Debug.Print Format(Now, "YYYY-MM-DD")

Dim sToday As String
sToday = CStr(Date)
That gives sToday value, e.g. "2020-12-31", in the format of my system's date.

In some VBA, the Format() function is not available. In this case, you can do it the old fashion:
y = cstr(year(now))
m = right("0" + cstr(month(now)),2)
d = right("0" + cstr(day(now)),2)
mydate = y + "-"+ m + "-" + d

Related

Split date/time not working when 12:00:00 AM

I have vba function to split date/time on my worksheet
but when it find 0:00AM it will stop and I don't know how to fix this
code
Function extractDateTime(strTime As Date) As Variant
Dim arrD, d As String, t As Date
arrD = Split(strTime, " ")
d = arrD(0)
t = CDate(arrD(1) & " " & arrD(2))
extractDateTime = Array(d, t)
End Function
pic when it find date/time at 12:00:00 AM
function not return value arrD(1) and arrD(2)
cell value
pic when function normally working
Always handle date/time as Date, not text, not numbers, no exceptions. So:
Public Function ExtractDateTime(Value As Date) As Variant
Dim d As Date
Dim t As Date
d = DateValue(Value)
t = TimeValue(Value)
ExtractDateTime = Array(d, t)
End Function
Parsing the Date for spaces is not a great way to go about it.
Instead, you can use Format to just get the pieces you want.
Function extractDateTime(dt As Date) As Variant
Dim d As String, t As String
d = Format(dt, "dd/mm/yyyy")
t = Format(dt, "hh:mm:ss AMPM")
extractDateTime = Array(d, t)
Debug.Print d
Debug.Print t
Debug.Print Format(dt, "mmm dd, yyyy")
Debug.Print Format(dt, "mmmm")
Debug.Print WeekdayName(Weekday(dt))
End Function
Kinda seems like a waste of a function tho when you can just do this:
Result = Array(Format(dt, "dd/mm/yyyy"), Format(dt, "hh:mm:ss AMPM"))

Problem of wrong date format when scraping date content from web by VBA Selenium

I try to scrape date underformat of "dd/mm/yy" from web to excel by VBA Selenium library.
Sheets("Sheet1").range("A1").value = driver.FindElementById("table-body-scroll").FindElementsByTag("tr").FindElementsByTag("td")(3).Text ' to get the 3rd col
The date value on web is formated as "dd/mm/yyyy" but when I scrape them to Excel, it turns to mm/dd/yyyy
How to force Excel to understand the date as "dd/mm/yyyy"
The url I navigate is: https://iboard.ssi.com.vn/bang-gia/chung-quyen
The column contains the date I get is the 3rd col named "GDCC"
Dim DateAry() As String
DateAry = Split(driver.FindElementById("table-body-scroll").FindElementsByTag("tr").FindElementsByTag("td")(3).Text, "/")
Range("A1").Value = DateAry(1) & "/" & DateAry(0) & "/" & DateAry(2)
Range("A1").NumberFormat = "dd/mm/yyyy"
or
Dim DateAry() As String
DateAry = Split(driver.FindElementById("table-body-scroll").FindElementsByTag("tr").FindElementsByTag("td")(3).Text, "/")
Range("A1").Value = DateAry(1) & "-" & DateAry(0) & "-" & DateAry(2)
Range("A1").NumberFormat = "DD-MM-YYYY"
I like to use this function I wrote. It returns a date object. Handles the year being 4 or 2 numbers long (i.e 2020 or 20). And doesn't care which "-" or "/" separator you use.
Function convert_date_to_uk(dte)
Dim days, months, weeks As String
months = Left(dte, 2)
If Len(dte) = 10 Then
years = Right(dte, 4)
Else
years = Right(dte, 2)
End If
days = Mid(dte, 4, 2)
convert_date_to_uk = DateSerial(years, months, days)
End Function
Then it can be used as follows with your example
Sheets("Sheet1").range("A1").value = convert_date_to_uk(driver.FindElementById("table-body-scroll").FindElementsByTag("tr").FindElementsByTag("td")(3).Text)

Date Format for Macro

I wrote a Macro to simplify a process at work.
I am trying to figure out how to fix this date so when the macro is run it isn't missing an "."
ex)
here is my code:
Dim currentDate As String
currentDate = Left(Replace(Date, "/", "."), 5) + Right(Date, 2)
To format date as a string use Format function and specify the format in a string. For instance:
Format(Date, "yyyy-mm-dd") 'gives 2020-01-08
I believe the following should add the desired dot:
Dim currentDate As String currentDate = Left(Replace(Date, "/", "."), 5) & "." & Right(Date, 2)

VBA format date to get the previous month

I am fairly new at VBA and this seems like an easy task. I am just trying to get the current date substituting the current month for the previous one and a day constant as 21 so the result will have to be yyyy - (m-1) - 21
so far I had a couple of ideas and they work partially
Sub Test_Date()
Dim x As String
Dim p As String
p = Format(Date, "mm") - 1
x = Format(Date, "yyyy-" p "-21")
End Sub
if I MsgBx "p" comesback as what I want but, I dont know the correct syntax to concatenate them into one string
also
Sub Test_Date()
Dim x As String
x = Format(Date, "yyyy-(Format(Date, "mm") - 1)-21")
End Sub
You could also try this:
Function LastMonth() As Date
Dim d As Date
d = DateAdd("m", -1, Date)
LastMonth = DateSerial(Year(d), Month(d), 21)
End Function
Edit:
Format the returned date as needed:
Sub Test()
MsgBox Format(LastMonth, "yyyy-mm-dd")
End Sub
You could use DateSerial.
This accepts a year, month and day as its input and kicks out the date based on that.
So, DateSerial(2017,9,22) will give todays date.
To get the 21st of last month you'd use
DateSerial(Year(Date), Month(Date) - 1, 21)
Year(Date) returns 2017, Month(Date) returns 9.
Use the dateadd function (https://www.techonthenet.com/excel/formulas/dateadd.php):
DateAdd( interval, number, date )
or
DateAdd("m", 5, "22/11/2003")
Try
Sub Test_Date()
Dim d As Date
d = "22-09-2017"
d = DateSerial(Year(d), Month(d) - 1, 21)
End Sub

Formatting a number to two digits even if the first is a 0 vba

I would like to be able to use VBA to display any number between 1-24 as a 2 digit number. Obviously the only ones that have a problem with this are 1-9 which I would like displayed as 01, 02, 03, etc. Is there a way to perform this?
You cannot format an integer variable, you need to use a string variable for formatting.
You can convert the day part of a date to a format with leading zeros using the Day function to extract the day number from the date, and then using the Format function with a "00" format to add a leading zero where necessary
Format(Day(myDate), "00")
myDate is a Date variable containing the full Date value
The following macro can be used as a working sample
Sub Macro1()
Dim myDate As Date
myDate = "2015-5-1"
Dim dayPart As String
dayPart = Format(Day(myDate), "00")
MsgBox dayPart
End Sub
Sure you can format an integer, you just convert it to string within the format command:
formattedIntAsString = Format(Cstr(intValue), "00")
I did it like this:
number_item = 2
number_item = WorksheetFunction.Text(number_item, "00")
This will do the job.
I know it's old, but, to answer the question as clarified, I would use in the built in date formatting functionality.
To modify DeanOC's answer:
Sub Macro1()
Dim dateDate As Date
Dim strDate As String
Dim strDay As String
dateDate = "2015-5-1"
strDate = Format(dateDate, "mm/dd/yy") ' = "05/01/15"
strDay = Format(dateDate, "dd") ' = "01"
MsgBox "The two digit day of """ & strDate & """ is """ & strDay & ""."
End Sub

Resources