簡體   English   中英

MS Word 中的宏更新表格單元格出現問題 Header

[英]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 宏,其中速記屬性是ActiveWorksheetActiveWorkbook等。但是只有當您在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM