【问题标题】:How can I prevent a runtime error from occurring when pasting text from a Word document to Excel using VBA?使用 VBA 将文本从 Word 文档粘贴到 Excel 时,如何防止出现运行时错误?
【发布时间】:2022-06-28 02:03:12
【问题描述】:

使用此代码,我尝试将两个不同的文本字符串从 Excel 电子表格导出到 Word,使用 Word 比较功能突出显示和下划线两者之间的差异,然后将最终字符串以格式导出回Excel 电子表格。在大多数情况下,此代码有效。然而,当这段代码在列中运行时,有时当程序到达 ActiveSheet.Paste 行,它给了我一个错误(如图 1 所示)。

        Dim previous As String: previous = Cells(i, 19).Value
        Dim current As String: current = Cells(i, 20).Value

        Dim wordApp As Word.Application: Set wordApp = New Word.Application
        wordApp.Visible = True

        Dim firstdoc As Word.Document: Set firstdoc = wordApp.Documents.Add
        firstdoc.Paragraphs(1).Range.Text = previous

        Dim seconddoc As Word.Document: Set seconddoc = wordApp.Documents.Add
        seconddoc.Paragraphs(1).Range.Text = current

        Dim lastdoc As Word.Document
        Set lastdoc = wordApp.CompareDocuments(firstdoc, seconddoc, wdCompareDestinationNew)
        With lastdoc.ActiveWindow.View.RevisionsFilter
            .Markup = wdRevisionsMarkupAll
            .View = wdRevisionsViewFinal
        End With

        lastdoc.Content.FormattedText.Copy

        Cells(i, 20).Activate
        Cells(i, 20).Select
        PAUSE 3
        ActiveSheet.Paste 'Where the program always stops for some reason.

        firstdoc.Close SaveChanges:=wdDoNotSaveChanges
        seconddoc.Close SaveChanges:=wdDoNotSaveChanges
        lastdoc.Close SaveChanges:=wdDoNotSaveChanges
        wordApp.Visible = False

现在,这似乎不是一个真正的错误,因为当我点击调试和 F5(继续)时,它又开始正常工作了。如果我有 30 行文本,这可能会在整个程序执行过程中发生 5-6 次。我不确定是什么导致了这个问题。我知道它与它正在处理的文本范围无关,因为此错误随机发生在行的下方,有时是在粘贴大块文本或有时粘贴小块文本时。有人建议我使用 PAUSE 3 子程序来减慢程序的速度,以便 Excel 赶上。我猜它确实降低了错误消息的频率,但并没有完全摆脱它。如果有人可以给我一个关于发生了什么以及如何解决它的提示,那将非常有帮助!谢谢!

Sub PAUSE(Period As Single)
Dim t As Single
Period = 0.5
t = Timer + Period
Do
DoEvents
Loop Until t < Timer
End Sub

【问题讨论】:

  • 这是一个典型的适合我的方法示例:stackoverflow.com/a/60582628/478884
  • @TimWilliams 仅当我使用剪贴板时才这样做?另外,我不确定我是否理解代码试图做什么。不就是跳过有错误的行继续下一个吗?
  • 请参阅下面的尝试建议

标签: excel vba ms-word


【解决方案1】:

如果粘贴失败,您可以重试粘贴 - 当一次粘贴尝试有时失败时,这对我一直有效:

    Dim i As Long, pasted As Boolean
    '...
    '...
    lastdoc.Content.FormattedText.Copy
    pasted = False                'reset paste status flag
    For i = 1 To 10               'try 10 times to paste
        On Error Resume Next      'ignore any paste error
        ActiveSheet.Paste Destination:=ActiveSheet.Cells(i, 20)
        pasted = (Err.Number = 0) 'no error = pasted OK
        On Error GoTo 0           'stop ignoring errors
        If pasted Then Exit For   'exit if pasted OK
        DoEvents
    Next i
    
    If Not pasted Then 'was there a problem pasting?
        MsgBox "Problem pasting!"
    End If
    '...
    '...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多