[英]Trouble with Macro Updating Table Cells in MS Word Header
我正在开发一个宏,它将根据我存储在 excel 中的值更新 MS Word header 中表格的单元格。希望这将加快手动更新包含项目阶段和截止日期的标题的过程我正在使用的 100 多个单词的文档。 我对 VBA 知之甚少,但将这段代码拼凑在一起,希望知道他们在做什么的人能给我指明正确的方向,让这段代码正常工作。 如果有帮助,很乐意提供更多信息。 谢谢!
更新:感谢所有为使它正常工作而提供建议的人——由于某种原因仍然出现错误。 在识别和编辑 header 中的表格时遇到一些问题。
我在这一行收到错误 5941 - 请求的集合成员不存在
With oWordDoc.Sections(1)...
这是我得到的:
Sub UpdateSpecHeaders()
Dim oWordApp As Object
Dim oWordDoc As Object
Dim sFolder As String, strFilePattern As String
Dim strFileName As String, sFileName As String
'> Folder containing files to update
sFolder = Range("A20").Value
'> Identify file extension to search for
strFilePattern = "*.doc"
'> Establish a Word application object
On Error Resume Next
Set oWordApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set oWordApp = CreateObject("Word.Application")
End If
Err.Clear
On Error GoTo 0
oWordApp.Visible = True
Application.ScreenUpdating = False
'> Loop through the folder to get the word files
strFileName = Dir$(sFolder & strFilePattern)
Do Until strFileName = ""
sFileName = sFolder & strFileName
'> Open the word doc
Set oWordDoc = oWordApp.Documents.Open(sFileName)
'> Update Header
With oWordDoc.Sections(1).Headers(wdHeaderFooterPrimary).Range.Tables(1).Range
.Cells(Row:=3, Column:=1).Text = Range("A3").Value
.Cells(Row:=3, Column:=2).Text = Range("B3").Value
End With
'> Save and close the file
oWordDoc.SaveAs Filename:=oWordDoc.Name
oWordDoc.Close SaveChanges:=False
'> Find next file
strFileName = Dir$()
Loop
'> Quit and clean up
Application.ScreenUpdating = True
oWordApp.Quit
Set oWordDoc = Nothing
Set oWordApp = Nothing
End Sub
我收到错误 424 - Object Required on this line
With ActiveDocument.Sections(1)...
这是因为您从 Excel 运行 VBA 宏,其中速记属性是ActiveWorksheet
、 ActiveWorkbook
等。但是只有当您在 Word 中运行代码时, ActiveDocument
属性才有意义。 因此,应更改以下代码:
'> Update Fields
oWordApp.ActiveDocument.Fields.Update
'> Update Header
With ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Tables(2)
.Cell(Row:=3, Column:=1).Text = Range("A3").Value
.Cell(Row:=3, Column:=2).Text = Range("B3").Value
End With
它应该是这样的:
'> Update Fields
oWordApp.ActiveDocument.Fields.Update
'> Update Header
With oWordApp.ActiveDocument.Sections(1).Headers(wdHeaderFooterPrimary).Range.Tables(2)
.Cell(Row:=3, Column:=1).Text = Range("A3").Value
.Cell(Row:=3, Column:=2).Text = Range("B3").Value
End With
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.