I export two strings of text from an Excel spreadsheet to Word, use the Word Compare function to highlight and underline the differences between the two, and then export that final string with the formatting back to the Excel spreadsheet.
When this code runs down the column, sometimes the ActiveSheet.Paste
line, gives me
Run-time error '1004':
Microsoft Excel cannot paste the data.
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
When I hit debug and F5 (Continue), it begins to work again like normal. If I have 30 rows of text, this might occur 5-6 times throughout the program execution. I know it has nothing to do with the extent of text it's handling because this error occurs randomly down the row, sometimes when pasting a large block of text or sometimes pasting a small block of text.
Someone suggested that I use the PAUSE 3 Subroutine to slow down the program for Excel to catch up. It did decrease the frequency of the error message.
What could be going on and how do I fix it?
Sub PAUSE(Period As Single)
Dim t As Single
Period = 0.5
t = Timer + Period
Do
DoEvents
Loop Until t < Timer
End Sub