VBA无法将Date转换为字符串

时间:2017-11-09 09:45:30

标签: vba excel-vba excel

我有一张excel表,它会计算出单元格中当前的星期日。

我使用宏来处理工作表内的数据。 但我无法读出日期并将其转换为字符串。

运行时错误'13':类型不匹配。 在线sDate =

Sub Dateit()

    Dim sDate As String
    'Formula inside cell Q5: =Today()
    'Formula inside merged cells Q6:R6: =INT((Q5-1)/7)*7+1
    'Shows the String: 5-Nov-2017 in cells q6:r6

    sDate = Format(Range("Q6:R6").Value, "dd. mmm yyyy")
    MsgBox sDate

End Sub

1 个答案:

答案 0 :(得分:2)

如果您的示例中有多个值/日期,那么我建议您使用这样的数组:

Option Explicit

Sub Dateit()

Dim sDate() As Variant
Dim x As Long, y As Long

'Load all dates into an array
sDate() = ActiveSheet.Range("Q6:R6").Value

'Iterate through all the "rows" of the array (dimension 1)
For y = LBound(sDate, 1) To UBound(sDate, 1)
    'Iterate through all the "columns" of the array (dimension 2)
    For x = LBound(sDate, 2) To UBound(sDate, 2)
        'refomrat the values as dates
        sDate(y, x) = Format(sDate(y, x), "dd. mmm yyyy")
        'show the dates in a message box
        MsgBox sDate(y, x)
    Next x
Next y

End Sub