我有大约100个需要更改页眉和页脚的文档。
我是否可以通过在word文件中编写vba代码或宏来实现?
是否可以在宏中为特定文件夹提供ll为该页脚中的所有文档添加页眉和页脚?
以下代码给了我
错误-5111
Private Sub Submit_Click()
Call openAllfilesInALocation
End Sub
Sub openAllfilesInALocation()
Dim i As Integer
With Application.FileSearch
.NewSearch
.LookIn = "C:\MyFolder\MySubFolder"
.SearchSubFolders = False
.FileName = "*.xls"
.Execute
For i = 1 To .FoundFiles.Count
'Open each workbook
Set Doc = Documents.Open(FileName:=.FoundFiles(i))
'Perform the operation on the open workbook
'wb.Worksheets("sheet1").Range("A1") = Date
'Save and close the workbook
With ActiveDocument.Sections(1)
.Headers(wdHeaderFooterPrimary).Range.Text = "Header goes here"
.Footers(wdHeaderFooterPrimary).Range.Text = "Footer goes here"
End With
Doc.Save
Doc.Close
'On to the next workbook
Next i
End With
End Sub
答案 0 :(得分:3)
在您提供的代码中,您尝试使用旧的.FileSearch
属性。它曾经工作到MS Office 2003,但现在不行。这里为您改进了代码。它将打开一个标准文件窗口,您可以在其中选择一个或几个要处理的文件。
Sub openAllfilesInALocation()
Dim Doc
Dim i As Integer
Dim docToOpen As FileDialog
Set docToOpen = Application.FileDialog(msoFileDialogFilePicker)
docToOpen.Show
For i = 1 To docToOpen.SelectedItems.Count
'Open each document
Set Doc = Documents.Open(FileName:=docToOpen.SelectedItems(i))
With ActiveDocument.Sections(1)
.Headers(wdHeaderFooterPrimary).Range.Text = "Header goes here"
.Footers(wdHeaderFooterPrimary).Range.Text = "Footer goes here"
End With
Doc.Save
Doc.Close
Next i
End Sub