I am trying to run a script that searches for a keyword, then copies the entire sentence where that keyword is found, and pastes it on an excel spreadsheet.
When I run the script on a document that is 1-2 pages, it runs fine, but when I am try a much longer document (100+ pages), I get the following error:
Run-time error '1004': Paste method of Worksheet class failed. When I click "debug" it says "objsheet.paste" is the problem.
Could you please help me fix the code so that it can work with longer text, too?
Sub FindWordCopySentence()
Dim appExcel As Object
Dim objSheet As Object
Dim aRange As Range
Dim intRowCount As Integer
intRowCount = 1
Set aRange = ActiveDocument.Range
With aRange.Find
Do
.Text = "Hair"
.Execute
If .Found Then
aRange.Expand Unit:=wdSentence
aRange.Copy
aRange.Collapse wdCollapseEnd
If objSheet Is Nothing Then
Set appExcel = CreateObject("Excel.Application")
Set objSheet = appExcel.workbooks.Open("C:\Users\HNR\Desktop\hair.xlsx").Sheets("Sheet1")
intRowCount = 1
End If
objSheet.Cells(intRowCount, 1).Select
objSheet.Paste
intRowCount = intRowCount + 1
End If
Loop While .Found
End With
If Not objSheet Is Nothing Then
appExcel.workbooks(1).Close True
appExcel.Quit
Set objSheet = Nothing
Set appExcel = Nothing
End If
Set aRange = Nothing
End Sub
aRange.CopytomyTempText = aRange.Text, andobjSheet.Cells(intRowCount, 1).SelectobjSheet.PastetoobjSheet.Cells(intRowCount, 1).Value = myTempText- that might help determine whether it is a copy/paste related problem or something else. (I can't replicate the problem with some dummy data that I set up, so I'm thinking there might be something in your document itself which is causing problems with copy/paste) - YowE3K