Excel vba: Convert String to Datetime add it to new Column - excel

So I have cells containing strings of date, such as:
14/04/2019 10:13:18 AM
how can I convert it to DateTime using vba?
I've tried using .NumberFormat but some of the cells got converted and some didn't:
My code is
Sub ConvertToDateTime()
With Range("Data[Modified On]")
.NumberFormat = "dd/mm/yyyy hh:mm:ss AM/PM"
.Value = .Value
End With
End Sub
And how do I insert converted value to a new column?
I've created a new column with:
Dim Table As ListObject
Dim newColNum As Integer
Set Table = ActiveSheet.ListObjects("Data")
Table.ListColumns.Add.Name = "New Header"
Can I do it without looping?

Some of the cell do got converted but some don't
That's because the date format on your PC is different than the data (it is mm/dd/yyyy while the data is in "dd/mm/yyyy")
This can't be fixed without looping. (as far as I know)
To fix that, you might need to do something like this:
Sub ConvertToDateTime()
Dim Cell As Range, h As Long, c As Long
Range("Data[New Header]").NumberFormat = "dd/mm/yyyy hh:mm:ss AM/PM"
c = Range("Data[New Header]").Column
For Each Cell In Range("Data[Modified On]")
If Right(Cell.Value, 2) = "PM" Then h = 12 Else h = 0
Cells(Cell.Row, c).Value = DateSerial(Mid(Cell.Value, 7, 4), Mid(Cell.Value, 4, 2), Left(Cell.Value, 2)) + _
TimeSerial(Mid(Cell.Value, 12, 2) + h, Mid(Cell.Value, 15, 2), Mid(Cell.Value, 18, 2))
Next
End Sub

Related

Cannot change the format after concatenating dates in Excel VBA

I have dates formatted as text. I want to change these dates' format from
"dd.mm.yyyy hh:mm" to "yyyy.mm.dd". (eg. "04.05.2020 10:33" to "2020.05.04") I use the following code (the original dates are in column "K"):
Dim cell As Range
For Each cell In Range(Range("K2"), Range("K2").End(xlDown))
cell.Offset(0, 7).Value = Mid(cell.Value, 7, 4) & "." & Mid(cell.Value, 4, 3) & Left(cell.Value, 2)
Next
The newly created dates cannot be formatted, though and so when I try to use a vlookup function on them, the function fails, saying it couldn't find the value in the lookup table. (dates are ok in the lookup table)
I need to manually enter every cell and hit enter and only after that will excel start recognizing the format.
I also found that if I use the manual "replace" function of excel like this: https://i.stack.imgur.com/U3k5e.png, and replace the dots with dots, excel will once again start to recognize the format, however it won't recognize any format when I use the following code:
Range(Range("R2"), Range("R2").End(xlDown)).Replace What:=".", Replacement:=",", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
Can someone help? How can I convert the format of these concatenated values in vba so that vlookup will recognize them?
Thanks!
Try this:
cell.Offset(0, 7).Value = Format(Mid(cell.Value, 7, 4) & " " & Mid(cell.Value, 4, 3) & " " & Left(cell.Value, 2), "yyyy.mm.dd")
The yyyy.mm.dd at the end tells it how you want it formatted. You also need to use a space or a slash (/) between the 3 functions because it doesn't recognize a period as a separator for it.
For example formatting the month. Take January:
m = 1
mm = 01
mmm = Jan
mmmm = January
Edit:
The only way I could see really doing it then is:
Dim cell as range
For Each Cell in Range(Range("K2"), Range("K2").End(xlDown))
Cell.Value = Format(Replace(Cell.Value,".","/"), "yyyy.mm.dd")
Next
Convert Date & Time As String to Date
Option Explicit
Sub createDate()
Dim Data As Variant
Dim currString As String
Dim currDate As Date
Dim i As Long
With Range(Range("K2"), Range("K2").End(xlDown))
Data = .Value
For i = 1 To UBound(Data, 1)
currString = Data(i, 1)
currDate = DateSerial(CLng(Mid(currString, 7, 4)), _
CLng(Mid(currString, 4, 2)), CLng(Left(currString, 2)))
Data(i, 1) = currDate
Next i
With .Offset(, 7)
.Value = Data
.NumberFormat = "yyyy.mm.dd"
'.Columns.AutoFit
End With
End With
End Sub
I ended up using the following code:
For Each cell In Range(Range("K2"), Range("K2").End(xlDown))
cell.Offset(0, 7).Value = Mid(cell.Value, 7, 4) & "/" & Mid(cell.Value, 4, 2) & "/" & Left(cell.Value, 2)
Next
Turns out I just had to use slashes to separate the concatenated parts, this allowed me to freely change the formatting of the newly created dates.
Special thanks to Simon, his answers helped a lot!

Excel VBA - when subtracting two dates VBA sees them as numbers

I use Excel 2013.
When I subtract two dates in excel "1.11.2019" and "1.10.2019" I get the result 31 as you should.
But when I do the same thing in VBA I get 10000. So it sees them as regular numbers "1112019" and "1102019". How can I get the same result in VBA too?
Use DateDiff() function with d interval to get days difference between two date. Try like below.
Sub DateSubstract()
MsgBox DateDiff("d", Range("B1"), Range("A1"))
End Sub
You may have to format the string into a Date format
Dim diff As Long
Dim strDate1, strDate2 As String
Dim fDate1, FDate2 As Date
Set sh = ThisWorkbook.Sheets("myDate")
' convert in string with 8 caracters
strDate1 = Right("0" & sh.Range("A1").Value, 8)
strDate2 = Right("0" & sh.Range("B1").Value, 8)
'format Year, month, day
fDate1 = DateSerial(Right(strDate1, 4), Mid(strDate1, 3, 2), Left(strDate1, 2))
fDate2 = DateSerial(Right(strDate2, 4), Mid(strDate2, 3, 2), Left(strDate2, 2))
diff = DateDiff("d", fDate2, fDate1)
Debug.Print ("difference :" & diff)

Convert date from dd.mm.yyyy format to dd-mmm-yyyy

Recently I've been trying to write a macro code for converting a range of dates in dd.mm.yyyy to dd-mmm-yyyy format.
So, I first replaced the "." with "-" and used numberformat = dd-mmm-yyyy
There seems to be an error in the output as it is giving month as date and date as month, e.g., 07.01.2020 is showing as 01-Jul-2020.
Following is the code:
sub dateformat()
range("A2").replace what:="." replacement:="-"
range("A2").numberformat = "dd-mmm-yyyy"
end sub
Kindly help if there's a solution to this.
Give this a try:
Sub fixdate()
Dim s As String
With Range("A2")
s = .Text
.Clear
.NumberFormat = "dd-mm-yyyy"
.Value = DateSerial(Right(s, 4), Mid(s, 4, 2), Left(s, 2))
End With
End Sub

Cut and Paste a Portion of a String Using a Macro

I need a macro to cut and paste a portion of a string from column A to column B if the string has a - sign in the 9th character. I found some code on stackoverflow that will copy/paste the text portion but does not cut/paste. My data looks like this
SUBIAIUP-456253
SUBIAIUP-254
Here's the code I have so far:
Public Sub LeftSub()
Dim cell As Range
Dim sourceRange As Range
Set sourceRange = Sheet1.Range("A1:A180")
For Each cell In sourceRange
If Mid(cell.Value, 9, 1) = "-" Then
'this code should cut/paste the value from col A to col B, not copy/paste
Sheets("Sheet1").Range("B" & cell.Row).Value = Mid(cell.Value, 9, 20)
End If
Next
End Sub
Any help is much appreciated.
Thank you.
If you want the value you are pasting into column B removed from column A, use this:
If Mid(cell.Value, 9, 1) = "-" Then
cell.Offset(, 1).Value = Mid(cell.Value, 9)
cell.Value = Left(cell, 8)
End If
As Sid and Brett point out, we don't need the number of characters argument for the Mid function if we are getting the rest of the value from the midpoint on. If you want the dash at the start of your Column B value, set the midpoint to 9. If you want to omit it, set it to 10.
If you want to cut/paste the entire value from column A to B, use this:
If Mid(cell.Value, 9, 1) = "-" Then
'this code WILL cut/paste the value from col A to col B, not copy/paste
cell.Cut cell.Offset(, 1)
End If

How do I convert a number like 20120103 into a date that Excel can recognize?

I have an 8 digit number that tells me the date, YYYYMMDD. How can I convert this number into a date that Excel will recognize as a date.
Let's assume cell A1 has 20120229 in it...what do I do?
Since you tagged this question VBA, I assume you want an answer in VBA, so here you go:
Dim l As Long
Dim s As String
Dim d As Date
l = Range("A1").Value ' 20120229
' convert it to a string
s = CStr(l)
' can now use string functions to parse it
d = DateSerial(CInt(Left(s, 4)), CInt(Mid(s, 5, 2)), CInt(Right(s, 2)))
' d is now 29 Feb 2012
' write it back to the sheet
Range("A2").Value = d
Use this formula: =DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2)) where A1 is the cell coordinate.
I like being able to select text in excel and call a macro to do the work.
Sub YYYYMMDDToDate()
Dim c As Range
For Each c In Selection.Cells
c.Value = DateSerial(Left(c.Value, 4), Mid(c.Value, 5, 2), Right(c.Value, 2))
'Following line added only to enforce the format.
c.NumberFormat = "mm/dd/yyyy"
Next
End Sub

Resources