2012-04-15 42 views
1

我需要一個字符串變量轉換爲日期變量在VBA宏,處理,以獲得mMonth的日期和年份,以命名轉換字符串變量迄今爲止

Call GetMonthandYear(MonthYear, FileDate) 
    ActiveSheet.Name = MonthYear 

我尋找到工作表創建一個名爲GetMonthandYear的方法。 FileDate是日期格式的字符串,dd.MM.yyyy HH-mm-ss。如果我可以將變量更改爲日期,我可以將格式更改爲MMMM/yyyy,然後使用ToString,我認爲將其分配給MonthYear

有沒有辦法將字符串更改爲日期?

回答

2

有幾個問題,你提出的aaproach:

  1. 將字符串轉換爲日期序列是有問題的,有不確定性,如果Excel將其解釋日期dd.MMMM.dd。由於您事先知道該格式,因此直接提取月份和年份。
  2. \對於圖紙名稱不是有效的字符。我用_,替代品如你所願

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 

這樣稱呼它

Sub Test() 
    Dim FileDate As String 
    FileDate = "15.04.2012 16-31-18" 

    ActiveSheet.Name = GetMonthandYear(FileDate) 

End Sub 
0

您是否嘗試過使用CDate和Format函數?

+0

從來沒有聽說過CDATE,但剛纔發現ToDateTime方法目前實驗 – 2012-04-15 13:35:48

0

您可以使用CDate功能獲取日期,但需要將-替換爲:.以替換爲/

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 
+0

看來你的方法應該工作,但我不斷geting類型不匹配'Sub GetMonthandYear(MonthYear,FileDate) Dim dateBuf As Date dateBuf = CDate(Replace $(FileDate,「 - 」,「:」)) End Sub' – 2012-04-15 13:58:13