【发布时间】: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 仅当我使用剪贴板时才这样做?另外,我不确定我是否理解代码试图做什么。不就是跳过有错误的行继续下一个吗?
-
请参阅下面的尝试建议