I want to use VBA code to convert my data (date) from text to date.
For Each c In Range("B4:B" & Range("B" & Rows.Count).End(xlUp).Row)
c.Value = DateValue(c.Value)
Next c
This code is not working with blank cells in between. Showing runtime error (error in datatype). And this code:
For Each c In Range("B4:B" & Range("B" & Rows.Count).End(xlUp).Row)
c.Value = CDate(c.Value)
Next c
is showing 12.00.00 AM for empty values.
Basic idea behind to convert all text to date in given range, when new data is pasted.
Please give suggestions. Thanks
You can try this as well : Isdate function checks if a value is date or not.
For Each c In Range("B4:B" & Range("B" & Rows.Count).End(xlUp).Row)
if Isdate(c.value) then
c.Value = CDate(c.Value)
Else End if
Next c
Here is a two line code (This doesn't require looping)
Sub Sample()
[A1:A20].NumberFormat = "DD/MM/YYYY"
[A1:A20] = [index(IF(A1:A20="","",DATEVALUE(A1:A20)),)]
End Sub
I am assuming that the range is from A1:A20
Please change as applicable.
If you want to understand what this code does then see the explanation that I have given Here
This is a combination of INDEX
and =IF(A1="","",DATEVALUE(A1))
From what I can gather, you have a range of cells with data you wish to convert to dates, but some of the cells in that range are blank? What do you want to do with the blank cells?
If you want to ignore them, just add an IF statement to cater for them
For Each c In Range("B4:B" & Range("B" & Rows.Count).End(xlUp).Row)
If c.Value <> "" Then
c.Value = DateValue(c.Value)
End If
Next c
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.