编辑页眉中的文本框(第一页不同)



EDIT:我可以让它在单独的文档中工作,但不能基于模板文档。

我试图在循环中编辑一个模板创建文件的标题中的文本框。文本框名称是";文本框2;它的框内已经有文本。目标是用字符串CountryName2替换其中一个单词("COUNTRYNAME"((见下面的完整子帖子(。以下是实际进入并编辑文本框的相关代码:

Set tFile = Documents.Add(tPath)
Selection.InsertFile (cDirPath & "" & cFile)
Debug.Print tFile.Sections(1).Headers(wdHeaderFooterFirstPage).Shapes.Range(Array("Text Box 2")).TextFrame.TextRange.Text 'This will print the text within the textbox with DebugPrint but if I try to set it = to something and get rid of Debug.Print (allegedly to edit/add text) nothing happens

我可以使用简单的tFile.Sections(1).Headers(wdHeaderFooterFirstPage).Range.Text = "Replaced Header Text"编辑页眉中的文本但它用文本替换了整个标题(我已经在标题上有很多东西不想更改了——只有一个也是唯一的文本框。

整个子文件:子文件的目的是打开一个目录中的一堆文件,将它们复制到一个新的模板文档中,然后更改模板标题以匹配文件名中的国家/地区名称。

Sub CopyAndPaste()
Dim tPath As String 'template path string
Dim tFile As Document 'template file
Dim cDirPath As String 'copy directory Path
Dim cName As String 'name of copy
Dim CountryName As String ' country name1
Dim CountryName2 As String ' country name2
Dim pDir As String
Dim findTextH As String
findTextH = "COUNTRYNAME"
pDir = "C:UsersXXXXXXXDesktopTestSaved"
With Application.FileDialog(msoFileDialogFilePicker) 'pick the template document path
.ButtonName = "Pick Template"
.Title = "Pick the template"
If .Show <> 0 Then
tPath = .SelectedItems(1)
End If
End With

With Application.FileDialog(msoFileDialogFolderPicker) 'pick the directory with the files path
' show the file picker dialog box
If .Show <> 0 Then
cDirPath = .SelectedItems(1)
End If
End With
cFile = Dir(cDirPath & "" & "*.docx")
Do While cFile <> ""
cName = GetFilenameFromPath(cFile) 'get the original file name without path

CountryName = Mid(cName, 19)
CountryName2 = Left(CountryName, Len(CountryName) - 5)
Set tFile = Documents.Add(tPath)
Selection.InsertFile (cDirPath & "" & cFile)
Debug.Print tFile.Sections(1).Headers(wdHeaderFooterFirstPage).Range.Text

'.Shapes.Range(Array("Text Box 2")).TextFrame.TextRange.Text = "Testing" ***FOR TESTING&***

tFile.SaveAs2 FileName:=pDir & cName
tFile.Close
cFile = Dir

Loop
End Sub

我解决了这个问题。这是因为第二页页眉上有一个隐藏的文本框,把事情搞砸了。文本框中充满了白色文本!!!结果不知怎么搞明白了。

最新更新