Hi
I am relatively new to VBA and would be grateful for some help to refer a table in the document header. The code immediately below works fine but when I add this code to a for each loop it generates the runtime error 5941 " the requested member of the collection does not exist" at the .Range.Tables(1).Cell(1, 2).Range.Text = "test" line. The purpose of the code is to loop through each Word file in a folder, insert text into some fields of a table in the document header, and save the changes.
This works
This does not work
Any help would be really appreciated.
Caroline
I am relatively new to VBA and would be grateful for some help to refer a table in the document header. The code immediately below works fine but when I add this code to a for each loop it generates the runtime error 5941 " the requested member of the collection does not exist" at the .Range.Tables(1).Cell(1, 2).Range.Text = "test" line. The purpose of the code is to loop through each Word file in a folder, insert text into some fields of a table in the document header, and save the changes.
This works
VBA Code:
With ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary)
.Range.Tables(1).Cell(1, 2).Range.Text = "test"
'etc
End With
This does not work
VBA Code:
Sub Test()
Dim FSO As Object
Set FSO = CreateObject("Scripting.filesystemobject")
Dim folder As Object
Dim fpath As String
Dim myFile As Object
Dim strFileExt As String
strFileExt = ".docx"
Dim strSearch2 As String
Dim strSearch1 As String
Dim lngPosition1 As Long
Dim lngPosition2 As Long
'Returns lngPosition1 of first space
lngPosition1 = InStr(ActiveDocument.Name, " ")
strSearch1 = Left(ActiveDocument.Name, lngPosition1)
'Returns lngPosition1 of last full stop
lngPosition2 = InStrRev(ActiveDocument.Name, ".")
strSearch2 = Left(ActiveDocument.Name, lngPosition2)
Set fDialog = Application.FileDialog(msoFileDialogFolderPicker)
fDialog.Title = "Select a folder"
fDialog.InitialFileName = "G:\.........”
If fDialog.Show = -1 Then
fpath = fDialog.SelectedItems(1)
Set folder = FSO.GetFolder(fpath)
End If
For Each myFile In folder.Files
If InStr(1, myFile.Name, strFileExt, vbTextCompare) > 0 Then
Documents.Open (myFile)
With activedocument.Sections(1).Headers(wdHeaderFooterPrimary)
.Range.Tables(1).Cell(1, 2).Range.Text = "test"
'etc.
End With
Exit For
End If
Next
End Sub
Any help would be really appreciated.
Caroline