I keep getting a mix of two errors: Runtime Error '5941' The Requested Member of Collection Does Not Exist and Object variable not set (Error 91) for this code.
I am trying to look for a word in tables 8 and 9 in the document and if found, copy and paste its corresponding row in a new doc.
Dim z As Long
Dim v As Long
Dim Table As Table
Dim Tables As Tables
Dim Rows As Rows
Dim Row As Row
For z = 8 To 9 Step 1
For v = 1 To ActiveDocument.Tables(z).Rows.Count Step 1
ActiveDocument.Tables(z).Rows(v).Select
Selection.Find.Execute FindText:="apples"
If Selection.Find.Found = True Then
ActiveDocument.Tables(z).Rows(v).Select
Selection.Copy
ChangeFileOpenDirectory _
"C:".Activate
Selection.EndKey wdStory
Selection.PasteAndFormat (wdFormatOriginalFormatting)
End If
Next
Next
Try this code - you should be more explicit regarding the documents you are working on:
Sub copyRowsWithApples()
Dim docSource As Word.Document
Set docSource = ThisDocument 'adjust this e.g. ActiveDocument if applicable.
Dim docTarget As Word.Document
Set docTarget = Application.Documents.Add 'adjust this to your settings
Dim z As Long
Dim tbl As Table
Dim tblRow As Row
For z = 8 To 9 Step 1
Set tbl = docSource.Tables(z)
For Each tblRow In tbl.Rows
With tblRow.Range.Find
.Execute findtext:="apples"
If .Found = True Then
tblRow.Range.Copy
With docTarget.Content
.Collapse wdCollapseEnd
.PasteAndFormat wdFormatOriginalFormatting
End With
End If
End With
Next
Next
End Sub