问题
I need to convert a string variable to a date variable in a VBA macro, to process the date to get the mMonth and year in order to name the worksheet
Call GetMonthandYear(MonthYear, FileDate)
ActiveSheet.Name = MonthYear
I looking to create a method called GetMonthandYear. FileDate is a String in a date format, dd.MM.yyyy HH-mm-ss. If I can change the variable to a date, I can change the format to MMMM/yyyy and then use ToString, I think, and assign it to MonthYear.
Is there a way to change the string to a date?
回答1:
There are several problems with your proposed aaproach:
- Converting strings to date serial can be problematic, with uncertanty if Excel will interpret the date as
dd.MMorMM.dd. Since you know the format in advance, extract the month and year directly. \is not a valid character for sheet names. I've used_, substitute as you wish
Function GetMonthandYear(FileDate As String) As String
Dim dot1 As Long, dot2 As Long
Dim m As String, y As String
dot1 = InStr(FileDate, ".")
dot2 = InStr(dot1 + 1, FileDate, ".")
m = Mid$(FileDate, dot1 + 1, dot2 - dot1 - 1)
y = Mid$(FileDate, dot2 + 1, InStr(FileDate, " ") - dot2 - 1)
GetMonthandYear = Format$(DateSerial(y, m, 1), "MMMM_yyyy")
End Function
Call it like this
Sub Test()
Dim FileDate As String
FileDate = "15.04.2012 16-31-18"
ActiveSheet.Name = GetMonthandYear(FileDate)
End Sub
回答2:
Have you tried using the CDate and Format functions?
回答3:
You can get Date using CDate function but it requires - to be replaced by : and . to be replaced by /.
Dim yourStringDate, sBuf As String
Dim yourDateVariable As Date
yourStringDate = "15.04.2012 16-31-18"
sBuf = Replace$(yourStringDate,"-", ":")
sBuf = Replace$(sBuf, ".", "/")
yourDateVariable = CDate(sBuf)
MsgBox yourDateVariable
来源:https://stackoverflow.com/questions/10162424/convert-string-variable-to-date