VBA dates collected correctly but output wrongly - excel

I grab dates from one spreadsheet and output them onto another spreadsheet. After grabbing the date, when I debug.print it is in the correct format. When I output the date, debug.print also displays the correct format. However, the format on the spreadsheet the value has just been sent to, doesnt show the correct format.
I am using:
Sheets(SheetName).Cells(RowNum, ColNum).Value = Data
Sheets(SheetName).Cells(RowNum, ColNum).NumberFormat = "dd/mm/yyyy"
after I have pasted the value, but the months and days are still switched the wrong way.
Is there something I am doing wrong?? If I right click the cell it thinks it's date is dd/mm/yyyy but instead of 4th Sept it is showing 9th April.

This might be some trouble with localization:
Try using NumberFormatLocal, if DanielCooks tip didn't help ;)
edit: erlier it was statet by mister Cook, to check if the given data is correct.
edit:
With my german version I have quite some trouble to use / as the seperator, that is why i tryied with this code .NumberFormat ="dd-mm-yyyy;#" - works fine; I can switch days and month as I like.
edit:
With .NumberFormatLocal = "TT/MM/JJJJ" I have to use the german shorts for day, month and year, but now I can use / as the seperator.
You should experiment a litte bit with some formats strings ;)

Sorry to resurrect an old post, however I had a problem with VBA outputting a valid date as US style with the actual date changed for example 1st May changed to 5th Jan. I came upon this post but I didn't find the answer I needed here and now that I have worked it out I thought I would share it:
The key is not to define the variable storing the date as a "date" but as a "double", e.g.
Dim ReportDate As Double
ReportDate = Date
Range("E6").Value = ReportDate
This works as it outputs the numeric "date value" which excel then formats locally e.g. 41644 gets formatted as "05/01/14" using UK format or "01/05/14" using US format.
Hope this proves useful to other people (probably me when I forget how I solved it in six months time).

In the end I had to format the cell as "TEXT" to keep the correct format

(1) You need to define the variable to "Date" type to read the input, then set the date format before assigning it to the date variable.
(2) You also need to format the date output to make it work !
'**Read the date input****
Dim date1 as Date
Range("B2").NumberFormatLocal = "dd/mm/yyyy"
date1 = Range("B2").Value
'**Output the date****
Range("E2").Value = date1
Range("E2").NumberFormatLocal = "dd/mm/yyyy"

Related

How can I format a string into a date: time format?

For example:
2021-08-18T22:24:49-06:00
I want to print this to a more readable format like: 8/18/21 10:24pm
I have tried using the built in DateTime function but it returns an error. Can someone point me in the right direction? I have checked other answers but they all relate to using the aforementioned funciton.
Looking at how your data is formatted and it seems your data is formatted "yyyy-mm-ddThh:mm:ss";so, here is my attempt:
Formula in C1:
=--SUBSTITUTE(LEFT(A1,16),"T"," ")
Then I just formatted the resulting datetime-stamp with:
m/d/yy hh:mm AM/PM
So it remains a numeric value to do your calculations with if needed.
Give a try to below formula-
=TEXT(FILTERXML("<t><s>"&SUBSTITUTE(A1,"T","</s><s>")&"</s></t>","//s[1]")+FILTERXML("<t><s>"&SUBSTITUTE(FILTERXML("<t><s>"&SUBSTITUTE(A1,"T","</s><s>")&"</s></t>","//s[2]"),"-","</s><s>")&"</s></t>","//s[1]"),"M/dd/yyyy hh:mm AM/PM")
The date is in ISO 8601 format. This will parse out the different parts of the date string and convert to a date, assuming that your string is in A1:
=DATEVALUE(LEFT(A1,10))
+TIMEVALUE(MID(A1,12,8))
+TIMEVALUE(RIGHT(A1, 5))
*INT(MID(A1, 20, 1) & 1)
The first part grabs the date, the second part grabs the time, the third part captures the date offset, and the last part captures the sign. If you want to format that, you can do it with the cell formatting or wrap it in TEXT:
=TEXT(
DATEVALUE(LEFT(A1,10))
+TIMEVALUE(MID(A1,12,8))
+TIMEVALUE(RIGHT(A1, 5))
*INT(MID(A1, 20, 1) & 1),
"yyyy-mm-dd hh:mm:ss"
)
Note that if you need to support UTC, that is indicated by Z instead of a time offset, and you would need to modify the formula slightly. If your data always has the same time offset, you could just hardcode it, instead of parsing it out.

VBA Date + TimeValue returns no time

I have a date and time which I assemble into a date + time from strings in the form
date_string = "2020-12-30" 'yyyy-mm-dd
date_code = CDate(date_string)
time_string = "00:00:00" 'hh:mm:ss
time_code = TimeValue(time_string)
date_time = date_code + time_code
Commonly the return looks like 05.01.2019 11:00:00, which is what I expect.
The returned values also all check out as TRUE if I test with IsDate(date_time)
Whenever the time is 00:00:00 however, I only get the date returned with no time appended. I dont quite understand this, since TimeValue(time_string)returns 00:00:00.
So it must be an issue when combining date and time to a date + time string.
Can someone please enlighten me why midnight somehow does no exist in Excel VBA or where my error in creating the time code is?
EDIT:
I try to explain my situation a bit better:
I do this date date/time stuff in code and then but the result in an array in a loop. Only later on it is written to a cell in a table.
By the time is is written into a cell, even custom formatting the cell to "DD.MM.YYYY hh:mm" does not show the time as it is completely missing from the cell value.
Do I neet to apply a format at the point of date_code + time_code?
Sometimes the answer can be so simple. Thanks to Variatus and Paul I checked formatting out.
I applied a date_time = Format(date_code + time_code, "dd.mm.yyyy hh:mm") in my code. Using this, my code runs as expected and 00:00:00 appears as expected, even in the cell values of the Excel table.
When you enter an integer, like 43930, in a cell Excel will record the number as an integer, just as you entered it. You can then proceed to format the cell as #,##0.000 and thereby make the number display as 43930.000. Or you can format that very same number as custom dd mmm yyy hh:mm:ss and display it as 09 Apr 2020 00:00:00. The point is that Excel chose to record the number in its most efficient way, as an integer.
So, if you enter a DateValue + TimeValue which, together, amount to an integer Excel will record the integer correctly. The format in which that integer is displayed in your worksheet is a matter for cell formatting.

Excel wont recognize date using openpyxl

I have a piece of code that converts a unix date to standard U.S. date format. It displays properly in excel, however excel doesn't recognize it as a date.
if str(startdate).isdigit():
startdate = int(startdate)
date = datetime.datetime.fromtimestamp(int(startdate)).strftime('%m/%d/%Y')
ws4.cell(row=cell.row,column=2).value = date
ws4.cell(row=cell.row,column=2).number_format = 'MM DD YYYY'
Any idea how to get excel to see this as a date rather than text?
My mistake was assuming the line below created a date.
date = datetime.datetime.fromtimestamp(int(startdate)).strftime('%m/%d/%Y')
After venturing into the docs (Scary as hell for a noob. Does it get easier?) I realized .strftime('%m/%d/%Y') created a string not a date.
I converted that string to a date using:
date = datetime.datetime.strptime(date, '%m/%d/%Y').date()
Now excel recognizes it as a date.
Hopefully this helps someone in the future.

Change text to specific date format + Excel VBA

I want to change so many dates saved as text in excel sheets to Arabic (Hijri) date format, ie; dd/mm/yyyy to (right to left) yyyy/mm/dd .. it can be done manually be change custom format from Number Format panel ( by choosing the location , calendar type and the right format from list ) then replace the text in cell by same value ..
I need VBA code to automate this replacement process for any ltr date and for existing rtl date just convert the format from general to date ..
another problem , there is some other text around the date in cell like ( dd/mm/yyyy ttt ) . I want the code to remove this text (ttt) ( any text ) and then change to the right format
I found this code but it is not work to my specific need
Changing the date format to yyyy-mm-dd
I appreciate any help , thanks in advance ..
You have a number of separate problems and it is unrealistic to expect someone else to have posted a complete solution to that set of problems or that someone will code a complete solution for you. You need to split your total problem into its components and create or look for a solution to each component.
You have strings that contain CE dates in the format “dd/mm/yyyy”. These dates could be surrounded by text. You give the example “dd/mm/yyyy ttt”. Can ttt contain spaces? Could the “ttt” come before the date? Could the string be as complicated as “aaaa bbbb cccc 12/11/2016 dddd eeee ffff”?
Whatever the situation, I suspect something like:
Dim Part() As String
Part = Split(.Cells(R, C).Value," ")
would be the core of first step. With my complicated example, this would give:
Part(0) = "aaaa"
Part(1) = "bbbb"
Part(2) = "cccc"
Part(3) = "12/11/2016"
: : : :
A loop over the parts of each cell value looking for a string for which IsDate gives True would allow you to find the date so .Cells(R, C).Value = Part(N) would delete the unwanted text.
I would take a copy of your data and try to code a macro that discards the unwanted text. If you can successfully create that macro, you have completed step 1 of your solution. If you have trouble with this macro, you can ask for help here and expect to get it.
The next step is to convert the string “dd/mm/yyyy” to an Excel date. Excel holds dates as the number of dates since 1/1/1900 CE. Replacing:
.Cells(R, C).Value = Part(N)by .Cells(R, C).Value = CDate(Part(N))ought to do the trick. However, Excel sometimes tries to interpret “dd/mm/yyyy” dates as “mm/dd/yyyy”. I think you will be alright but be aware of this possibility.
Your last step is to convert a date from the CE calendar to the Hijri calendar. This is not just a format issue. The two calendars have different year zeroes and different month lengths. There may be a standard conversion function in your country but there does not appear to be one here in the UK. There is help online so you should be able to find a function that will perform the conversion.
You have a number of separate problems and it is unrealistic to expect someone else to have posted a complete solution to that set of problems or that someone will code a complete solution for you. You need to split your total problem into its components and create or look for a solution to each component.
You have strings that contain CE dates in the format “dd/mm/yyyy”. These dates could be surrounded by text. You give the example “dd/mm/yyyy ttt”. Can ttt contain spaces? Could the “ttt” come before the date? Could the string be as complicated as “aaaa bbbb cccc 12/11/2016 dddd eeee ffff”?
Whatever the situation, I suspect something like:
Dim Part() As String
Part = Split(.Cells(R, C).Value," ")
would be the core of first step. With my complicated example, this would give:
Part(0) = "aaaa"
Part(1) = "bbbb"
Part(2) = "cccc"
Part(3) = "12/11/2016"
: : : :
A loop over the parts of each cell value looking for a string for which IsDate gives True would allow you to find the date so .Cells(R, C).Value = Part(N) would delete the unwanted text.
I would take a copy of your data and try to code a macro that discards the unwanted text. If you can successfully create that macro, you have completed step 1 of your solution. If you have trouble with this macro, you can ask for help here and expect to get it.
The next step is to convert the string “dd/mm/yyyy” to an Excel date. Excel holds dates as the number of dates since 1/1/1900 CE. Replacing:
.Cells(R, C).Value = Part(N)by .Cells(R, C).Value = CDate(Part(N))ought to do the trick. However, Excel sometimes tries to interpret “dd/mm/yyyy” dates as “mm/dd/yyyy”. I think you will be alright but be aware of this possibility.
Your last step is to convert a date from the CE calendar to the Hijri calendar. This is not just a format issue. The two calendars have different year zeroes and different month lengths. There may be a standard conversion function in your country but there does not appear to be one here in the UK. There is help online so you should be able to find a function that will perform the conversion.
You have a number of separate problems and it is unrealistic to expect someone else to have posted a complete solution to that set of problems or that someone will code a complete solution for you. You need to split your total problem into its components and create or look for a solution to each component.
You have strings that contain CE dates in the format “dd/mm/yyyy”. These dates could be surrounded by text. You give the example “dd/mm/yyyy ttt”. Can ttt contain spaces? Could the “ttt” come before the date? Could the string be as complicated as “aaaa bbbb cccc 12/11/2016 dddd eeee ffff”?
Whatever the situation, I suspect something like:
Dim Part() As String
Part = Split(.Cells(R, C).Value," ")
would be the core of first step. With my complicated example, this would give:
Part(0) = "aaaa"
Part(1) = "bbbb"
Part(2) = "cccc"
Part(3) = "12/11/2016"
: : : :
A loop over the parts of each cell value looking for a string for which IsDate gives True would allow you to find the date so .Cells(R, C).Value = Part(N) would delete the unwanted text.
I would take a copy of your data and try to code a macro that discards the unwanted text. If you can successfully create that macro, you have completed step 1 of your solution. If you have trouble with this macro, you can ask for help here and expect to get it.
The next step is to convert the string “dd/mm/yyyy” to an Excel date. Excel holds dates as the number of dates since 1/1/1900 CE. Replacing:
.Cells(R, C).Value = Part(N)by .Cells(R, C).Value = CDate(Part(N))ought to do the trick. However, Excel sometimes tries to interpret “dd/mm/yyyy” dates as “mm/dd/yyyy”. I think you will be alright but be aware of this possibility.
Your last step is to convert a date from the CE calendar to the Hijri calendar. This is not just a format issue. The two calendars have different year zeroes and different month lengths. There may be a standard conversion function in your country but there does not appear to be one here in the UK. There is help online so you should be able to find a function that will perform the conversion.

Date format in vba

I have VBA code which pull the details from .msg file (outlook files) and update in excel sheet. While reflecting the date column, it is showing as "3/9/2016 11:03:27 AM" but I want to show only date and not time.
I used the format option i.e.
Sheet2.Cells(Row + 1, 23) = VBA.Format(sentDate, "dd/MM/yyyy")
but it is showing the date a "8/3/2016 00:00". I want to reflecting only date and nothing else. Please guide me as to what all changes required to reflect only date.
Give this a try:
Sheet2.Cells(Row + 1, 23).Value = sentDate
Sheet2.Cells(Row + 1, 23).NumberFormat = "mm/dd/yyyy;#"
Yet, I have a feeling that the cell does not really contain a date but merely text. So, please also try to change the .NumberFormat to the following first:
Sheet2.Cells(Row + 1, 23).NumberFormat = "General"
If the dates are now showing all as numbers then these are actual dates and the first proposal should work. If not, then these are not dates yet and you'll have to convert the text (which looks like dates) to dates first.
For more information you might want to read this: Difference between date and time w/out work week Excel

Resources