2013-03-20 77 views
1

我有大約100個需要更改頁眉和頁腳的文檔。爲許多單詞文檔添加頁眉和頁腳?

是否有可能通過在word文件中編寫vba代碼或宏來完成該操作?

是否可以給宏中的特定文件夾添加該頁腳中所有文檔的頁眉和頁腳?

下面的代碼給我

錯誤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 
+1

對於你所有的問題,我回答是!如果你嘗試任何東西,你需要任何幫助,你可以分享你的代碼,以獲得任何支持 – 2013-03-20 08:54:15

+0

Kaz Jaw請檢查代碼.... iam 5111錯誤... – 2013-03-20 09:46:46

回答

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 
+0

KazJaw ....非常感謝....它幫助我很大的時間.... – 2013-03-20 12:14:45

+0

對於在Google上發現這個問題的人來說,MSDN關於修改/訪問頁眉和頁腳的文章是一個很好的補充。 http://msdn.microsoft.com/en-us/library/ff194253(v=office.14).aspx – Kyle 2013-06-10 20:17:50