I am trying to convert the date format of my cells as the csv format they are delivered in shows a date but excel doesn't recognize it as a date (it shows "Standard" as format and the dates are aligned on the left, hence not dates in excel).
Dim lr11 As Integer
Dim dates11 As Date
lr11 = WS1.Cells(WS1.Rows.Count, "C").End(xlUp).row
For dates11 = 2 To lr11
WS1.Cells(dates11, 3).Value = CDate(Cells(dates11, 3).Value)
Next dates11
The above code sometimes works in a Test Sub() but when used in my main Sub, I always get "12:00:00 AM" in all cells instead of dates.
What am I doing wrong?
Thanks!
If you have strings that look like dates in the format DD.MM.YYYY you can split them and create a numeric date using DateSerial like below:
Option Explicit
Public Function ConvertStringDDMMYYYYtoDate(ByVal InputString As String) As Date
Dim RetVal As Date
Dim Parts() As String
Parts = Split(InputString, ".")
If UBound(Parts) = 2 Then
RetVal = DateSerial(Parts(2), Parts(1), Parts(0))
If Not Format$(RetVal, "DD.MM.YYYY") = InputString Then
MsgBox "Input String is not a real date", vbCritical
RetVal = 0
End If
End If
ConvertStringDDMMYYYYtoDate = RetVal
End Function
Then use it like
For dates11 = 2 To lr11
WS1.Cells(dates11, 3).Value = ConvertStringDDMMYYYYtoDate(WS1.Cells(dates11, 3).Value)
WS1.Cells(dates11, 3).NumberFormat = "DD.MM.YYYY" ' format it however you like it to look like
Next dates11
Related
I am iterating through dates in a loop to execute different snippets of code.The following piece of code in the loop gives me a
runtime error '6' Overflow
when assigning the cell's value to dateClaim:
Dim dateClaim As Date
Dim rngDateClaimeMade As Range
Set rngDateClaimeMade = dfensCSheet.Range("AC7") 'AC contains dates in format dd.mm.yyyy
dateClaim = rngDateClaimeMade.value
dateClaimMonth = Format(Month(dateClaim), "00")
dateClaimYear = Year(dateClaim)
Any ideas/ help is very much appreciated!
So that looks like 24.12.2020 is a text not a date in that cell and therefore it cannot be converted automatically.
If your dates are always in this format dd.mm.yyyy you can convert it like below:
Option Explicit
Public Sub Example()
Dim TextDate As String ' this is a text looking like a date (but is not a date just a string)
TextDate = "24.12.2020" ' instead read your cell value here
' test if the string has a format that we can convert
If Not TextDate Like "??.??.????" Then
MsgBox "Date was not in expected format dd.mm.yyyy"
Exit Sub
End If
' split text into 3 parts by dot as delimiter
Dim SplitDate() As String
SplitDate = Split(TextDate, ".")
' reorder the 3 parts to make a real numeric date
Dim NumericDate As Date
NumericDate = DateSerial(SplitDate(2), SplitDate(1), SplitDate(0))
' this numeric date is now a real date that can be formatted as desired
Debug.Print Format$(NumericDate, "yyyy-mm-dd") 'returns 2020-12-24
End Sub
You can then use
Dim dateClaim As Date
dateClaim = DateSerial(SplitDate(2), SplitDate(1), SplitDate(0))
Dim dateClaimMonth As String
dateClaimMonth = Format$(dateClaim , "mm")
Dim dateClaimYear As String
dateClaimYear = Format$(dateClaim , "yyyy")
if you need month and year as text! If you need them numeric don't use Format$()!
VBA cannot convert text dates with dots directly. So try:
dateClaim = DateValue(Replace(rngDateClaimeMade.Value, ".", "/"))
dateClaimMonth = Month(dateClaim)
dateClaimYear = Year(dateClaim)
Apply the format 00 where the month is to be displayed.
I'm exploring the use of Userform on my Excel VBA project and I want to create a form which will convert date from a DTPicker into text on a text box.
The reason for doing this is because I need the date to be in a specific format of yyyy/mm/dd to search an SQL query and the DTPicker value always default to dd-m-yyyy. Giving me no results in the query.
This is what I have so far:
Private Sub convertDate()
TextBox1 = DateFrmMac.Value
Me.TextBox1.Text = Format(Me.TextBox1.Text, "yyyy/mm/dd")
TextBox2 = DateToMac.Value
Me.TextBox2.Text = Format(Me.TextBox2.Text, "yyyy/mm/dd")
End Sub
During testing if the date is for example 29/1/2020, the conversion can work as intended. But if the day is below 12, like 8/11/2019, the day and month will mix up its values and give me the wrong date.
What can I do to prevent this from happening?
Private Sub convertDate()
Dim d As Date, strT1 As String, strT2 As String
strT1 = CStr(DateFrmMac.Value): Debug.Print strT1 'for 2019/12/5 use
d = DateSerial(Split(strT1, "/")(0), Split(strT1, "/")(1), Split(strT1, "/")
(2))
'for strT1 = "5/12/2019" use:
d = DateSerial(Split(strT1, "/")(2), Split(strT1, "/")(1), Split(strT1, "/")
(0))
Me.TextBox1.text = Format(d, "yyyy/mm/dd")
strT2 = CStr(DateToMac.Value)
d = DateSerial(Split(strT2, "/")(0), Split(strT2, "/")(1), Split(strT2, "/")(2))
Me.TextBox2.text = Format(d, "yyyy/mm/dd")
End Sub
Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
If Mid(TextBox1.Value, 4, 2) > 12 Then
MsgBox "Invalid date, please re-enter", vbCritical
TextBox1.Value = vbNullString
TextBox1.SetFocus
Exit Sub
End If
StartDate = DateSerial(Year(Date), Month(Date), Day(Date))
TextBox1.Value = Format(TextBox1.Value, "dd.mm.yyyy")
StartDate = TextBox1.Value
End Sub
This code works well for me and my colleagues to make sure the value entered in the textbox is a date. However, a colleague from a different country (but also with the dd.mm.yyyy date-format) gets weird results.
For example: If he enters 01.10.2017 the TextBox automatically format the date into 20.03.4917.
I suspect that in this case the entered value is not recognized as a date but as a number because 01102017 will transform into 20.03.4917 in Excel if you convert it as a date.
Does anyone have a suggestion or a guess how to work around this problem?
Thanks and best regards
You could split the date by . into an array ArrInput and then use DateSerial to make it a real date, that you can format.
Dim ArrInput As Variant
ArrInput = Split(TextBox1.Value, ".")
'StartDate = DateSerial(Year(Date), Month(Date), Day(Date)) 'I see no use in this at all
TextBox1.Value = Format$(DateSerial(ArrInput(2), ArrInput(1), ArrInput(0)), "dd.mm.yyyy")
StartDate = TextBox1.Value
The issue with Format(TextBox1.Value, "dd.mm.yyyy") is that here you let Excel guess which date format the string in TextBox1.Value is. It automatically casts into a number which is then converted into a string again.
To avoid date misunderstandings I recommend always to use the YYYY-MM-DD format according to ISO 8601. This is the only date format that is human readable and cannot be misunderstood. It also has benefits when sorting by dates that are actually strings.
To make your validation even more solid use something like:
Dim ArrInput As Variant
ArrInput = Split(TextBox1.Value, ".")
Dim ValidDate As Boolean
If UBound(ArrInput) = 2 Then 'make sure there are exactly two dots in the date
If ArrInput(1) > 0 And ArrInput(1) <= 12 And _ 'month <= 12
ArrInput(0) > 0 And ArrInput(0) <= 31 Then 'day <= 31
ValidDate = True
End If
Else
ValidDate = False
End If
If Not ValidDate Then
MsgBox "Invalid date, please re-enter in format dd.mm.yyyy", vbCritical
TextBox1.Value = vbNullString
TextBox1.SetFocus
Exit Sub
End If
TextBox1.Value = Format$(DateSerial(ArrInput(2), ArrInput(1), ArrInput(0)), "dd.mm.yyyy")
StartDate = TextBox1.Value
I do believe that your colleague enters the text string "01102017" without dots.
You might want to convert such kind of entries into a valid date:
' "01102017" => 01.10.2017 - 8 chars variant
' "011017" => 01.10.2017 - 6 chars variant
This needs to be done of cause prior to a date conversion.
Add a log of the input value to a free cell range and
have the workbook sent back to you:
...
Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
Range("Z1").value = "'" & TextBox1.Value
If Mid(TextBox1.Value, 4, 2) > 12 Then
...
Check if only numbers are used:
How to check if a string contains only numbers?
and check the length of the string (6 or 8 chars variant) and check if the year part is within a valid range => try to convert to a date and offer it to the user.
The date is supplied as a string in the form: 20180503
The function is supposed to validate that the entry is:
in the form YYYYMMDD
a valid date
The following code does not do the trick:
Function formatDateYYYYMMDD(dateStr As String, dateFormat As String) As String
Dim strToDate As Date
strToDate = CDate(dateStr)
If IsDate(strToDate) Then
formatDateYYYYMMDD= format(dateStr, dateFormat)
Else
formatDateYYYYMMDD= "Not a date"
End If
End Function
Perhaps:
edit: original UDF changed as it would not flag certain invalid format dates.
Option Explicit
Function formatDateYYYYMMDD(dateStr As String, dateformat As String) As String
Dim strToDate As Date
On Error GoTo invalidDate
If Len(dateStr) = 8 And _
Left(dateStr, 4) > 1900 And _
Mid(dateStr, 5, 2) <= 12 And _
Right(dateStr, 2) <= 31 Then
formatDateYYYYMMDD = Format(CDate(Format(dateStr, "0000-00-00")), dateformat)
Exit Function
End If
invalidDate: formatDateYYYYMMDD = "Not a date"
End Function
The On Error will pick up invalid dates that otherwise meet the format criteria: eg Sep 31, Feb 30
Interesting idea for a function. I've rewritten your code below to do exactly what you said. Function returns "Not a date" for 2018101a, 20181033, 201810300, otherwise returns date in formatted string. Note that you need to provide a valid string format and I did not handle that error. I assume there are no spaces at the end?
Function formatDateYYYYMMDD(dateStr As String, dateFormat As String) As String
Dim strToDate As Date
Dim day As Integer
Dim month As Integer
Dim year As Integer
On Error Resume Next
year = Left(dateStr, 4)
month = Mid(dateStr, 5, 2)
day = Right(dateStr, 2)
strToDate = DateSerial(year, month, day)
If Err.Number <> 0 Or Len(dateStr) <> 6 Then
formatDateYYYYMMDD = "Not a date"
Err.Clear
On Error GoTo 0
Else
On Error GoTo 0
formatDateYYYYMMDD = Format(strToDate, dateFormat)
End If
End Function
I fiddled with the code getting some directions from the guy's suggestion and it works now. Thanks, guys for all your input.
This is what I did
sValue = frmForm.txtSearch.Value
If IsDate(sValue) Then
'do nothing
Else
sValue = Format(frmForm.txtSearch.Value, "DD-MM-YYYY")
End If
If the input date is always in this format(YYYYMMDD), you can write a custom code to convert it into a string that can be converted to date using CDATE.
Remember to convert month to name of the month, and year to four digit year. In this way you are explicitly defining the month, year and the remaining one as date, if you keep them as two digit numbers they may be interpreted differently on difference systems (when you convert them using CDATE)
I recommend this format DD-MMM-YYYY
In your code instead of
strToDate = CDate(dateStr)
You have to write a custom function
And in place of
formatDateYYYYMMDD= format(dateStr, dateFormat)
Return just the dateStr and set the format of the cell where it is returned to YYYYMMDD
Platform: OS window 7
Excel: 2007
Issue : I had a .csv file with some data and date capture from other place. The data(date) is located in cell A2 having the category under Date. (e.g 18/3/2014)
Firstly there is this Locale (location), stated English (Singapore). I wanted to change it to English (United States)
After that then change the date format to "M/D/YYYY"
What i had tried:
ExcelApp.ActiveWorkbook.Sheet1.Range("A2").NumberFormat = "M/D/YYYY"
it prompted me run time error "438"
object doesn't support this property or method.
how can make it that it return me the cell value as "3/18/2014"?
If you look in A2 and see:
18/3/2014
then its either a String or a formatted date. it does not matter which ;run this to fix it:
Sub FixDate()
Dim s As String
With Range("A2")
s = .Text
ary = Split(s, "/")
.Value = DateSerial(ary(2), ary(1), ary(0))
.NumberFormat = "m/d/yyy"
End With
End Sub
EDIT#1
If you want to Dim ary, then:
Option Explicit
Sub FixDate()
Dim s As String, ary
With Range("A2")
s = .Text
ary = Split(s, "/")
.Value = DateSerial(ary(2), ary(1), ary(0))
.NumberFormat = "m/d/yyy"
End With
End Sub
Well, a CSV file is just a Comma Separated Value File, so it doesn't support any of the cell formatting that an XLS or XLSX file would. So what you can do is:
If it only contains a date.
Dim dt As Date : dt = cdate(Range("A2").Value)
Range("A2").Value = Format(dt, "MM/d/yyyy")
If it contains a date and time and you only want the date.
Dim dt As Date : dt = cdate(Range("A2").Value)
Range("A2").Value = FormatDateTime(dt, 2)
if it contains a date and time and you want both.
Dim dt As Date : dt = cdate(Range("A2").Value)
Range("A2").Value = FormatDateTime(dt)