I have a column in which date is displayed in the format yyyy/mm/dd hh:mm:ss. I want to change the date format of that column. I am trying to insert another column and copy the data of that column in the new column by using format. Please find below my code.
last_Row = Worksheets("sheet1").Range("A65536").End(xlUp).Row
Worksheets("sheet1").Range("B1").EntireColumn.Insert
For i = 2 To last_Row
lfd_value = Worksheets("sheet1").Range("C" & i).Value
lfd_val_upd = Format(lfd_value, dd/mm/yyyy)
Worksheets("sheet1").Range("B" & i).Value = lfd_val_upd
Next i
You should replace your Format with the following:
lfd_val_upd = Format(lfd_value, "dd/mm/yyyy")
Or if your dates are not formatted as dates the the following should work:
lfd_val_upd = Format(CDate(lfd_value), "dd/mm/yyyy")
EDIT:
Try the following code, I've tested it and it works for me, an example date I tried is 2018/02/01 12:05:00
:
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
'get the last row with data on Column B
ws.Range("B1").EntireColumn.Insert
For i = 2 To LastRow
lfd_value = ws.Range("C" & i)
lfd_val_upd = Format(CDate(lfd_value), "dd/mm/yyyy")
ws.Range("B" & i).Value = lfd_val_upd
Next i
End Sub
UPDATE:
Another possibility is that your dates are not formatted as they should, the following will pick the parts of the contents of the cell and then convert them parts to a date and enter that date into Column B as Text:
Sub foo2()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
'get the last row with data on Column A
ws.Range("B1").EntireColumn.Insert
For i = 2 To LastRow
yearnumber = Mid(ws.Cells(i, 3), 7, 4)
monthnumber = Mid(ws.Cells(i, 3), 4, 2)
daynumber = Left(ws.Cells(i, 3), 2)
LValue = DateSerial(yearnumber, monthnumber, daynumber)
lfd_val_upd = Format(CDate(LValue), "dd/mm/yyyy")
ws.Cells(i, 2).NumberFormat = "@"
ws.Range("B" & i).Value = lfd_val_upd
Next i
End Sub
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.