获取部分文本并转换为日期

时间:2015-09-03 14:08:27

标签: excel vba

试图删除" As Of:" "截至:07/31/2015"并将剩余的文本转换为日期。到目前为止,我有:

Sub FasFormat()
Dim period As Long
    period = Mid([B4], 8, 10)
    period.Value = CDate(period)
    [B4] = period
End Sub

但是我得到了无效的限定符错误。画出一个严肃的空白

2 个答案:

答案 0 :(得分:0)

试试这个..(我已经在这里替换了我自己的变量日期!)

Dim period As String
Dim Strmydate As String
Dim mydate As Date

    Strmydate = "As Of: 07/31/2015"
    period = Mid(Strmydate, 8, 10)
    mydate = CDate(period)
    MsgBox period

答案 1 :(得分:0)

Sub FastFormat()
Dim period As String
    period = Mid([B4], 8, 11)
    ' you can also use 
    ' period = Trim(Right([b4], Len([b4]) - WorksheetFunction.Search(": ", [b4])))
    period = CDate(period)
    [B4] = period
End Sub

period更改为字符串并删除.Value可解决问题 - 它会返回日期。注意我还将mid()扩展为11

此外,如果这些都在列中,您可以执行Text To Columns,完全避免使用VBA。只需突出显示单元格,转到数据 - >文本到列,并使用:作为分隔符。