【问题标题】:Convert string variable to date将字符串变量转换为日期
【发布时间】:2012-04-15 13:25:45
【问题描述】:

我需要在 VBA 宏中将字符串变量转换为日期变量,以处理日期以获取 mMonth 和 year 以便命名工作表

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

我希望创建一个名为 GetMonthandYear 的方法。 FileDate 是日期格式的字符串,dd.MM.yyyy HH-mm-ss。如果我可以将变量更改为日期,我可以将格式更改为MMMM/yyyy,然后使用ToString,我认为,并将其分配给MonthYear

有没有办法将字符串更改为日期?

【问题讨论】:

    标签: excel date-format vba


    【解决方案1】:

    您提出的方法存在几个问题:

    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
    

    【讨论】:

      【解决方案2】:

      您是否尝试过使用 CDate 和 Format 函数?

      【讨论】:

      • 从未听说过 CDate 但刚刚发现 ToDateTime 方法目前正在试验
      【解决方案3】:

      您可以使用 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
      

      【讨论】:

      • 看来你的方法应该有效,但我不断收到类型不匹配Sub GetMonthandYear(MonthYear, FileDate) Dim dateBuf As Date dateBuf = CDate(Replace$(FileDate, "-", ":")) End Sub
      猜你喜欢
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 2014-05-19
      • 2017-12-11
      • 2015-04-27
      • 2016-10-11
      • 2011-11-28
      相关资源
      最近更新 更多