excel中用vba例遍文件夹中的word文件并设置word文件中第二个表格的标题跨页重复显示同时修改列宽并替换文本
时间: 2023-04-04 12:04:54 浏览: 346
可以使用以下代码实现:
Sub LoopThroughFiles()
Dim MyFile As String
Dim MyFolder As String
Dim wdApp As Object
Dim wdDoc As Object
Dim wdTable As Object
'设置文件夹路径
MyFolder = "C:\MyFolder\"
'初始化Word应用程序
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = False
'循环遍历文件夹中的Word文件
MyFile = Dir(MyFolder & "*.docx")
Do While MyFile <> ""
'打开Word文档
Set wdDoc = wdApp.Documents.Open(MyFolder & MyFile)
'设置第二个表格的标题跨页重复显示
Set wdTable = wdDoc.Tables(2)
wdTable.Rows(1).HeadingFormat = True
wdTable.Rows(1).HeadingFormat = wdTrue
wdTable.Rows(1).AllowBreakAcrossPages = False
'修改列宽
wdTable.Columns(1).Width = InchesToPoints(1.5)
wdTable.Columns(2).Width = InchesToPoints(2)
wdTable.Columns(3).Width = InchesToPoints(1.5)
'替换文本
wdDoc.Content.Find.Execute FindText:="old text", ReplaceWith:="new text", Replace:=wdReplaceAll
'保存并关闭Word文档
wdDoc.Save
wdDoc.Close
'继续遍历下一个文件
MyFile = Dir
Loop
'关闭Word应用程序
wdApp.Quit
Set wdApp = Nothing
End Sub
阅读全文