VBA Date values when inserted to Excel cells change their format - vba

I have date variables formatted like: 25_December_2010
Once i use
Dim strDate As String
strDate = "25_December_2010"
strDate = Replace(strDate,"_"," ")
MsgBox strDate
Surely enough a MsgBox pops up and gives me: 25 December 2010.
However once i try to put the value into a cell for example:
Sheets("Sheet1").Range("A1").Value = strdate
Instead of populating the cell with: 25 December 2010; Excel acts on it's own accord and populates the cell with the vexing entry configuration: 25-Dec-2010!
How can I have my cell populated with no hyphen characters inbetween and not having the month name trimmed?

This code puts the date into A1 in the format you write that you want:
Option Explicit
Sub WriteDate()
Dim strDate As String
strDate = "25_December_2010"
strDate = Replace(strDate, "_", " ")
MsgBox strDate
With Sheets("Sheet1").Range("A1")
.Value = strDate
.NumberFormat = "dd mmmm yyyy"
End With
End Sub
I'm not sure if it is necessary, but for clarity, since strDate is a string data type, I would probably use
.Value = CDate(strDate)
Explicitly converting it to the Date data type, before writing it to the worksheet, might be of value in non-English versions, but I've not checked that specifically.

Use a custom date format:
Sheets("Sheet1").Range("A1").NumberFormat = "dd mmmm yy" //A1 = 25 December 10

The Excel sheet is not wrong, so stop saying it is. A date is a count of the number of days since a start date. So a date is a NUMBER. You can format it how you want.
This is VBA, excel is similar though the starting dates are different.
Date variables are stored as IEEE 64-bit (8-byte) floating-point numbers that represent dates ranging from 1 January 100 to 31 December 9999 and times from 0:00:00 to 23:59:59. Any recognizable literal date values can be assigned to Date variables. Date literals must be enclosed within number signs (#), for example, #January 1, 1993# or #1 Jan 93#.
Date variables display dates according to the short date format recognized by your computer. Times display according to the time format (either 12-hour or 24-hour) recognized by your computer.
When other numeric types are converted to Date, values to the left of the decimal represent date information while values to the right of the decimal represent time. Midnight is 0 and midday is 0.5. Negative whole numbers represent dates before 30 December 1899.
Date 8 bytes January 1, 100 to December 31, 9999
This is what recording it in Excel shows.
Selection.NumberFormat = "d mm yyyy"
This works here for me
Sub DateF()
Dim strDate As String
strDate = "25_December_2010"
strDate = Replace(strDate, "_", " ")
MsgBox strDate
Worksheets("Sheet1").Range("A1").NumberFormat = "dd mm yy"
Worksheets("Sheet1").Range("A1").Value = strDate
End Sub
I also changed it from sheet. to worksheet.

Related

VBA convert string with day and month name to date

I have a string of a date in french in long format like so:
mardi 7 juillet 2020
How can I convert it to a date type in VBA ? I tried using CDate, DateValue and DateSerial, but I couldn't figure it out. There must be a way if VBA has a Long Date format for dates. I just can't find anyone that was asking this conversion question with this format.
Note that I have a lot of dates since I am looping over many mails so I need a solution that is very general so a solution that takes into account all possible week days (lundi, mardi, ..., dimanche), all possible days 1 to 31 and months Janvier to Décembre and all possible years.
Thank you for your help.
I agree there should be an easier conversion. This function will strip out the weekday (which is superfluous) and then rely on VBA type conversion to get a Date type (NB. I have only tested this under a English(UK) regional setting).
Option Explicit
Public Function DateFromLongFormat(strLongFormatDate As String) As Date
Dim strDate As String
strDate = Right(strLongFormatDate, Len(strLongFormatDate) - InStr(1, strLongFormatDate, " "))
DateFromLongFormat = strDate
End Function
Tried it out using a simple test routine on today's date:
Sub TestDate()
Dim strToday As String
strToday = Format(Now(), "dddd dd mmmm yyyy")
Dim dt As Date
dt = DateFromLongFormat(strToday)
End Sub

Trying to get two dates, 24th of last month and 23rd of this month

I am trying to get two dates as variants so I can swap them in and out of an SQL query that runs every month (with different periods). I am trying to get the 24th of last month in "yyyy-mm-dd" format and the 23rd of the current month (when the procedure runs) in "yyyy-mm-dd" format. I have this code, but it is giving me 'wrong number of arguments' as error and I don't understand why.
Option Explicit
Sub mDateSet()
Dim fromDateFinal As String
Dim toDate As String
Dim toDateFinal As String
Dim fromDate: fromDate = Format(DateAdd("M", -1, Now), "yyyy-mmmm")
'Format gives 'wrong number of arguments or invalid property assignment error'
'trying to define two dates: the 24th of last month until the 23rd of this month)
'24th of last month
fromDateFinal = fromDate & "24"
Debug.Print fromDateFinal
'23th of this month
toDate = Format(Date, "yyyy-mm")
toDateFinal = toDate & "23"
Debug.Print toDateFinal
End Sub
Here are some string dates from manipulated dates and format masks.
fromDateFinal = format(date-day(date), "yyyy-mm-24") '2018-02-24
toDateFinal = format(date, "yyyy-mm-23") '2018-03-23
If Format(DateAdd("M", -1, Now), "yyyy-mmmm") produces that error (wrong number of arguments or invalid property assignment error) and does selecting Format, then there is another function Format defined somewhere in <Global>, which has less or more arguments.
Try VBA.Strings.Format(DateAdd("M", -1, Now), "yyyy-mmmm").
Strings.Format is the fully qualified name of the needed Format function.
If it does selecting DateAdd, then maybe the same for this. There the fully qualified name is VBA.DateTime.DateAdd.

Comparing US date to UK date

I'm using Excel VBA and want to verify 2 dates are the same. On my macro, the user enters a date in the mm/dd/yy format (01/31/15). When the macro runs, it opens a file submitted by a user in Europe. On that sheet, there is a date field where the date is entered in the dd/mm/yy format (31/01/15). I'm wondering if there is an easy way to compare these 2 dates to verify that they are the same.
I could convert one of the dates into the other format and then convert both to a date serical to see if they are the same. I wanted to check and see if there was an easier way or a function that could do that.
Thanks for the help........
So apparently the MSDN Library has a converter Sub:
Function MakeUSDate(DateIn As Variant) As String
' Do nothing if the value is not a date.
If Not IsDate(DateIn) Then Exit Function
' Convert the date to a U.S. Date format.
MakeUSDate = "#" & Month(DateIn) & "/" & Day(DateIn) & "/" & Year(DateIn) & "#"
End Function

Change date's format after loading it to UserForm textbox

I have a userform with textbox. When textbox is initialized it's getting filled with actual date. What I want to do is to fill it with custom date format = DD-MM-YYYY
I wrote code below and something is wrong about it but I have no idea what is wrong. Code has msgbox before inserting value, MsgBox shows date in a custom format but when it is passed to textbox.value it's like M/DD/YYY.
Dim year As Long, year_control As Date
year = Format(Date, "yyyy")
year_control = Format(Date, "dd-mm-yyyy")
MsgBox (year_control)
textbox.Value = year_control
(...)
If year_control < "01-04-" & year Then
Me.Controls("rok1").Value = True
Else
Me.Controls("rok2").Value = True
End If
You cannot "Format" a date variable:
year_control As Date
year_control = Format(Date, "dd-mm-yyyy")
The above code does nothing because a Date variable is simply holing a date more specifically VBA stores Date variables as IEEE 64-bit (8-byte) floating-point numbers that represent dates ranging from 1 January 100 to 31 December 9999 and times from 0:00:00 to 23:59:59.
No matter what you do to this variable it will always display dates according to the short date format recognized by your computer. Times display according to the time format (either 12-hour or 24-hour) recognized by your computer.
So while you can change the internal value that is held by the Date Variable you cannot store its format inside of the same vairable.
You can however display it however you would like inside of a string variable. So, if you used:
Dim year As Long, year_control As Date
Dim strYear_control As string
year = Format(Date, "yyyy")
year_control = Format(Date, "dd-mm-yyyy")
strYear_control = Format(year_control , "dd-mm-yyyy")
MsgBox (strYear_control)
textbox.Value = strYear_control
It should work as you are expecting. As the Format() function will return a Variant (String) containing an expression formatted according to instructions contained in a format expression.
As a side note you may also wish to use
Format$(year_control , "dd-mm-yyyy")
as it will be much faster, You also can use FormatDateTime to format your date in other various ways.

Format function vba changing date

The format function in vba is changing the date. e.g for format("3/12/2009","DD/MM/YYYY"), the function returns 12/03/2009 where "3/12/2009" is what excel vba reads from a cell that has the value 12-Mar-2009 and the format as "dd-mmm-yyyy"
No it's not.
If a date-as-string is passed to the Format function, it will parse it using current regional settings. Your settings are obviously MM/DD/YYYY which is default for USA. Nothing prevents Excel from displaying a date as DD/MM/YYYY if set manually, but by default it would display MM/DD/YYYY.
To do: Stop reading dates as strings. Read them as dates.
dim d as date
d = activecell.value
Had few times problem myself where VBA in Access reades most dates as europian but some as USA:
This DOES NOT work properly:
myRs.FindFirst ("Date =#" & myDate & "#")
This works:
myRs.FindFirst ("Date =#" & Format(myDate, "Long Date") & "#")
The long date (eg 01 January 2012) clearly makes the difference between month and day