我正在处理一个宏,它将根据我存储在excel中的值更新MS Word头中表格的单元格。希望这将加快手动更新我正在使用的100+ word文档中包含项目阶段和到期日的标题的过程。我对VBA知之甚少,但我把这些代码拼凑在一起,希望知道自己在做什么的人能给我指明正确的方向,让这段代码正常工作。如果有帮助,很乐意提供更多的信息。谢谢!
更新:感谢所有为使其正常工作而提供建议的人--由于某种原因仍然出现了错误。在识别和编辑标题中的表时遇到了一些问题。
在这一行中,我得到了错误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发布于 2022-03-16 15:16:25
我得到了这行需要的424对象错误
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 Withhttps://stackoverflow.com/questions/71489286
复制相似问题