Date display vs date format VBA - vba

I think that I try to do something what is impossible. I have in range A1:A5 some dates. These cells have to have date format, because I’d like to check if they are bigger or smaller than certain date. Moreover I’d like to display these dates in a range A1:A5 in a following format: yyyy.mm. I think that there is no way to kill two birds with one stone.
Public Sub test()
Range("A1:A5").NumberFormat = "yyyy.mm"
Range("A1:A5") = Format(Date, "yyyy.mm")
If IsDate("A2") Then
Range("B2") = "OK"
End If
End Sub
Range("B1:B5").NumberFormat = "yyyy.mm" change the cells format on custom (yyyy.mm) but the dates are still displayed in unchanged form (yyyy.mm.dd)
Range (“A1:A5”) = Format(Date, “yyyy.dd”) displays the dates yyyy.mm but the year and month has been changed to 1905.07. Moreover the dates do not have Date format but Custom.
Is is really not possible to display a date like yyyy.mm but in date format (so that in formular bar the date is displayed as dd.mm.yyyy or another way around) to be able to compare them with different dates?
Best regards,
Neke

First of all, using points within dates can be a problem, because "2017.05" is interpreted by Excel as a number.
You can reformat the dates into "yyyy/mm" by using something like this:
For Each r In Range("A1:A5")
r.Value = VBA.Format(r, "yyyy/mm")
Next r

Related

VBA: Hard Coding Dates to X axis in Date format

I'm having a problem with adding dates to a scatter chart. I'm using a string to add values to a chart's series collection (e.g.: Chart1.FullSeriesCollection(1).XValues = {date1,date2,date3})
It works great when I format the dates to a number value (e.g.: Format(xDate, "0"), but the X axis shows up as numbers instead of dates.
However, it does NOT work when the dates are left in date format (e.g.: Format(xDate, "MM/DD/YY").
I also tried ("#" & Format(xDate, "MM/DD/YY") & "#") to no avail.
Any Ideas? Hoping it's simple, and I'm just tired from working on my algorithm all day.
Formatted the X axis 'Number' to Category: Date (format code: "mm/dd/yyy"), and viola! The chart changes the date number values to the format I wanted to see.

changing date fromat from mm/dd/yyyy to dd/mm/yyyy VBA

So I know this question has been asked a couple of times over, but I believe my situation is a bit different (happy to be proven wrong of course!)
Here is the data flow: a user types a date in a date in a form. They then click a button. My macro then takes that date, runs it through the following function:
Function AddWeekDays(StartDate As Long, Days As Long) As Date
Dim i As Long
Dim d As Date
d = StartDate
i = 0
While i < Days
d = DateSerial(Year(d), Month(d), Day(d) + 1)
If Weekday(d, vbMonday) < 6 Then
i = i + 1
End If
Wend
AddWeekDays = d
End Function
Then it formats the date to change it from mm/dd/yyyy to dd/mm/yyyy in the following way:
Dim deadline As Date
Dim deadline_formatted As Date
Dim DateReceived As String
Dim DateConverted As Date
DateReceived = txt_DateReceived.Text
DateConverted = Format(DateReceived, "dd/mm/yyyy")
deadline = AddWeekDays(DateValue((CStr(DateConverted))), 9)
deadline_formatted = Format(deadline, "dd/mm/yyyy")
However, the deadline_formatted value is still coming out in the mm/dd/yyyy format.
As an example, when a user enters 01/05/2017 the program should return deadline_formatted = 12/05/2017, but it returns deadline_formatted = 05/12/2017
I have tried changing the variable type to string to see if that made a difference (it didn't), and have tried directly converting the deadline variable to the required format by using the following code:
deadline = Format(AddWeekDays(DateValue((CStr(DateConverted))), 9),"dd/mm/yyyy")
which still returns the incorrect format.
Can anybody out there suggest either:
How to fix the formatting issue to get the deadline_formatted into the format dd/mm/yyyy
OR
suggest a "workaround" to flip the "dd" with the "mm" (not ideal obviously, but if it works, it works!)
Thanks for any advice!
The best way to solve this issue is to actually change your computer's default date/time format to match the method used by the users. (In comments it is stated that the users are Australians but your company is US-based, so the default is probably currently set to be the USA's "mm/dd/yyyy" format.)
By ensuring that the computers date/time format is correct, it will allow you to process a date as a Date, and it can be stored in Excel cells as a Date, which then allows any of the Australian users to see it displayed as "dd/mm/yyyy" format while a USA-based colleague would see it displayed as "mm/dd/yyyy".
There is a financial risk to your company caused by forcing users to interact with software using an unfamiliar date system, as accidental entering of dates in the wrong formats can lead to major errors downstream, so it is in the company's best interest to allow you to change the settings to be relevant to the users.
It is not directly related to your problem, however I believe it might fix your issues. The manual calculation of adding week days might be the problem here.
There is a built in function to add workdays. You can include/exclude weekends/holidays. The following code replaces your above mentioned code.
Sub AddWeekDays()
Dim deadline As Date, deadline_formatted As Date
deadline = txt_DateReceived.Value
deadline_formatted = Format(Application.WorksheetFunction.WorkDay(deadline, 9), "dd/mm/yyyy")
'debug.print deadline_formatted
End Sub
the result to be String.
Dim deadline As Date
Dim deadline_formatted As String '<~~ change string
Dim DateReceived As String
Dim DateConverted As Date
txt_DateReceived = "01/05/2017"
DateReceived = txt_DateReceived
DateConverted = Format(DateReceived, "dd/mm/yyyy")
'deadline = AddWeekDays(DateValue((CStr(DateConverted))), 9)
deadline = AddWeekDays(CLng(DateConverted), 9) '<~~ change Long
deadline_formatted = Format(deadline, "dd/mm/yyyy")
I wouldn't bother about the regional settings. Instead, make sure that all dates are captured as Date() or Now() values (42123 or 42123.5555). On the output side such values can be presented in any format you wish.
To ensure that dates are entered correctly my preferred way is to use a date picker. If that can't be done make no rules for entering the date at all, working on the presumption that each user will know how to enter a date on his/her machine. Add a date check, like ISDATE(), which will catch some input errors but not all. You don't need to catch all. You only need to teach users how to input dates on their respective PCs.
With this line you don't need anything else.
Range("E:E").TextToColumns FieldInfo:=Array(0, xlDMYFormat)
'1.2.2019 -> 01/02/2019
'2,3,2019 -> 02/03/2019
'3-4-2019 -> 03/04/2019
'4*5*2019 -> 04/05/2019
'5_-6-*2019 -> 05/06/2019
'and so on
Of course you can change the format with
xlMDYFormat

Convert number in textbox to month name for vba statements

I have a textbox wherein I input number as months (like "01" for January) but I need the actual month name instead of the number in my VBA statements. Can you please help me convert the number in the textbox into Actual Month Name.
I have tried the statement below but it is not working:
Dim MoName As String
MoName = Format(Month(Monthtxtbx.Text), "MMMM")
Range("Cells(1,1):Cells(LastCol, Lastcolumn)").AutoFilter Field:=3, Criteria1:=MoName
Use MoName = MonthName(Monthtxtbx.Text) to get the month name.
Alternatively, you could dummy up a date so that you could use the "mmmm" format as:
MoName = Format(DateSerial(2000,Monthtxtbx.Text,1), "MMMM")
but that would be the long way to achieve something simple.

Changing date formats in Excel using

I have a excel sheet in which a column has date date in the format "yyyyMMdd" and I want to format it as "yyyy/MM/dd".
For this I tried to use following line inside macro, but it's converting cell data as "###.....#" instead of changing date format.
Sheet1.Range("C3", "C302").NumberFormat = "yyyy/mm/dd"
...
result = "#####...#"
...
Can someone tell me why it's happening? Is there any other way for doing this?
If a date/time cell appears full of # signs, it means that the column is too narrow to display the format.
Make the column wider to accommodate the full width of the selected date format.
See this screenshot. Both columns have the same format. Column A is too narrow to show the dates. Column B is wide enough.
Edit after discussing in chat:
The screen shot you posted in chat is this:
The "dates" you are referring to are not dates. They are numbers that are way higher than what Excel uses for dates in this millenium.
Excel stores dates as whole numbers, starting as 1 for 1/1/1900. What you show in your screenshot are numbers way higher than Excel dates.
Your number 20150930 is NOT what Excel considers Sep-30-2015. For Excel, that date would be the number 42277, which you can perfectly format as that date.
The reason that your "dates" formatted with your format string come out as ##### is that the numbers are way higher than what Excel can interpret as dates.
You will need to convert your numbers to real Excel dates, which you can do with a simple formula. With your first "date" number in cell A1, you can use the formula
=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2))
to return a value that Excel regards as a true date for Sep-30-2015 in this screenshot:
So, the reason for all the # signs is that the numbers you are trying to format as dates are too big for dates in Excel's algorithms.
With all the good answers, I will add simple vba solution...
Option Explicit
Sub FormatDate()
Dim xlRng As Range
Dim xlShtRng As Range
'//- Date format 20160112
Set xlShtRng = [A3:A10] '//- or [A3, A6, A10]
For Each xlRng In xlShtRng
xlRng.Value = DateSerial(Left(xlRng.Value, 4), Mid(xlRng.Value, 5, 2), Right(xlRng.Value, 2))
xlRng.NumberFormat = "yyyy/mm/dd" '//- 2016/01/12
Next
End Sub
Please try this..
=LEFT(A1,4)&"/"&MID(A1,5,2)&"/"&RIGHT(A1,2)

How to determine if a date is in the past?

I have an Excel workbook for tracking backup success. We have a number of sheets with the date in the first column, and macros to do calculations, based on whether the date is in the past or not. (The macros either hide or reveal the appropriate rows.)
This has been working until yesterday. I assume because the macros are doing a string comparison, rather than a date comparison. ("01/01/2013" is smaller than "12/31/2012", when viewed as strings.)
Is there a native way to compare dates in VBA, or do I need to convert the dates into "yyyy/mm/dd" first (a how to would be nice).
A2 is the cell with the first date we started using this new version of the spreadsheet, and A454 is the last date I extended the spreadsheet to, corresponding to the end of this year.
Sub ShowAll()
Dim cell As Range
For Each cell In Range("A2:A454")
cell.EntireRow.Hidden = False
Next
End Sub
Sub RevealPast()
Dim cell As Range
For Each cell In Range("A2:A454")
If cell.Value < Date Then
cell.EntireRow.Hidden = False
End If
Next
End Sub
Sub HideFuture()
Dim cell As Range
For Each cell In Range("A2:A454")
If cell.Value >= Date Then
cell.EntireRow.Hidden = True
End If
Next
End Sub
Try the cDate function.
something along the lines of:
If CDate("02/01/2013") > Date (or Now() if you want today's date) Then
...
So, in your example:
If cDate(cell.Value) >= Date Then
I hope I understand your question correctly and hope this helps...
I know this is a bit different from what you asked but this might help someone someday. If there is an hour added to the date (3/5/2014 8:00:00 AM) and you would like to compare with your date you can:
'X being the date you want to compare
x = CDate(x) 'formatting the date using the CDate function
x= Format(x, "MM/DD/YYYY") 'formatting the date by dropping the hour
x= CDate(x) 'formatting the date again
If x <= Date Then
...
I follow your answer and No ! No ! And No!
On Excel VBA, It's wrong ! you need to format the date like "2020/07/18 09:48:51" to can compare
So first get Date variable with CDate() function, and after, you can compare like that. Else it's not working.
If Format(MyFileDate, "yyyymmdd hhnnss") >= Format(ReportStart, "yyyymmdd hhnnss") And Format(MyFileDate, "yyyymmdd hhnnss") < Format(ReportEnd, "yyyymmdd hhnnss") Then