vba 为多个word文档添加页眉和页脚?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15518682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 20:08:27  来源:igfitidea点击:

To Add Header and Footer for many word documents?

vbams-wordheaderword-vbafooter

提问by Gokul Sundaravadivel

I have around 100 documents for which the header and footer need to be changed.

我有大约 100 个文档需要更改页眉和页脚。

Is there a possibility that i can do it just by writing a vba code or Macro in a word file?

是否有可能我可以通过在 word 文件中编写 vba 代码或宏来做到这一点?

Is it possible to give a specific folder in a macro which ll add the header and footer for all the documents in that footer?

是否可以在宏中提供一个特定文件夹,该文件夹将为该页脚中的所有文档添加页眉和页脚?

the below code gives me

下面的代码给了我

error-5111

错误-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

回答by Kazimierz Jawor

In the code you provided you have tried to use old .FileSearchproperty. It used to work until MS Office 2003 but not now. Here goes code improved for you. It will open a standard file window where you can pick one or few files to process.

在您提供的代码中,您尝试使用旧.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