字符串值未正确传递

String Value is not passing correctly

我有一句话table。我写了一个宏来从 table 中获取值。运行时出现运行时错误 13。当我调试并观察解析字符串的值时,它看起来像这样 "2019-04-03 字符串中只有一个引号。我我认为我无法将该字符串转换为日期格式。你能帮我解决这个问题吗?

代码

Sub Macro2()
    Dim NumRows As Integer
    Dim startDate As String
    Dim days As String
    Dim endDate As String

    If Not Selection.Information(wdWithInTable) Then
        Exit Sub
    End If

    NumRows = Selection.Tables(1).Rows.Count

    'Loop to select each row in the current table
    For J = 2 To NumRows
        'Loop to select each cell in the current row
            startDate = Selection.Tables(1).Rows(J).Cells(5).Range.Text
            days = Selection.Tables(1).Rows(J).Cells(6).Range.Text
            FormatDate = CDate(ends)
            endDate = DateAdd("d", days, FormatDate)
            Selection.Tables(1).Rows(J).Cells(7).Range.Text = endDate
    Next J
End Sub

table

这是我在 Word 2013 中测试时发现对我有用的最小更改。

总分:

  • 我加了Option Explicit是为了让电脑帮我找错误。在这种情况下,变量 JFormatDate 被使用但未被 Dimed,并且 ends 被使用但从未初始化(我将其更改为 startDate) .
  • table 单元格中的 Range.Text 包含空白和 table 结束标记 (¤)。这就是 CDate 给出错误的原因。
    • 对于日期,我使用 Left() 只取左边的十个字符,因为您似乎总是使用 yyyy-mm-dd 格式的日期。
    • 对于天数,因为天数可以是任意长度,我使用 Range.Words(1).Text 只保留第一个 Word(如 MS Word 定义的那样),即数字。
  • 我还在 DateAdd 的参数中添加了 CLng() 调用,因为 DateAdd 需要数字 * 而不是字符串。

对于生产用途,我还建议仅在一处使用 Selection,并执行 Dim workTable as Table: Set workTable = Selection.Tables(1)。这将简化您的代码。

代码

<=== 标记更改行

Option Explicit ' <==

Sub Macro2()
    Dim NumRows As Integer
    Dim startDate As String
    Dim days As String
    Dim endDate As String

    If Not Selection.Information(wdWithInTable) Then
        Exit Sub
    End If

    NumRows = Selection.Tables(1).Rows.Count

    'Loop to select each row in the current table
    Dim J As Long   ' <==
    For J = 2 To NumRows
        'Loop to select each cell in the current row
            startDate = Selection.Tables(1).Rows(J).Cells(5).Range.Text
            startDate = Left(startDate, 10) ' <== Remove the space and table mark
            days = Selection.Tables(1).Rows(J).Cells(6).Range.Words(1).Text     ' <===
            Dim FormatDate As Date          ' <==
            FormatDate = CDate(startDate)   ' <== not `ends`
            endDate = DateAdd("d", CLng(days), FormatDate)      ' <=== clng
            Selection.Tables(1).Rows(J).Cells(7).Range.Text = endDate
    Next J
End Sub

* DateAdd实际上取了一个Double,但是VBA可以将Long提升为Double。我选择了 CLng,因为看起来您只使用了整数天数。如果不是,请改用 CDbl

尝试:

Sub Demo()
Dim r As Long
With Selection
  If Not .Information(wdWithInTable) Then Exit Sub
  With .Tables(1)
    For r = 2 To .Rows.Count
      .Cell(r, 7).Range.Text = _
        Format(DateAdd("d", Split(.Cell(r, 6).Range.Text, vbCr)(0), CDate(Split(.Cell(r, 5).Range.Text, vbCr)(0))), "YYYY-MM-DD")
    Next r
  End With
End With
End Sub