簡體   English   中英

VBA訪問 - 查找和替換Word文檔中的文本

[英]VBA Access - Find and Replace text in Word Document

我已經在Excel中成功編寫了一些VBA代碼,它打開現有的Word文檔,根據Excel工作表中的信息查找並替換字符串。

由於源數據存在來自Access數據庫,我想我會嘗試將VBA代碼移動到Access中並從那里運行它。

更新的代碼主要起作用,但奇怪的是,當我在訪問中運行它時,查找和替換文本字符串的代碼部分不起作用。

Sub CreateFormsPDF()

'   Creates Garda Vetting Forms NVB1 in Word and saves as PDF
    Dim WordApp As Object
    Dim WordDoc As Object
    Dim db As Database
    Dim rs As Recordset
    Dim Records As Integer
    Dim IDAnchor As String
    Dim ID As String
    Dim FilePath As String, SaveAsName As String

    FilePath = "N:\"

'   Start Word and create an object (late binding)
'   Document already exists so reference this
    Set WordApp = CreateObject("Word.Application")
    Set WordDoc = WordApp.Documents.Open(FilePath & "Form1.docx")

    WordApp.Application.Visible = True

'   Point to the relevant table in the Current Database
    Set db = CurrentDb
    Set rs = db.OpenRecordset("qryMailingList", dbOpenDynaset, dbSeeChanges)
    Records = rs.RecordCount

'   Cycle through all records in MailingList Query
    Do Until rs.EOF

'   Define IDAnchor
    IDAnchor = "$$ID$$"

'   Assign current data to variables
    ID = rs!StudentID

'   Determine the filename
    SaveAsName = FilePath & ID & ".pdf"

'   Send commands to Word
    With WordApp
        With WordDoc.Content.Find
            .Text = IDAnchor
            .Replacement.Text = ID
            .Wrap = wdFindContinue
            .Execute Replace:=wdReplaceAll
        End With
        .ActiveDocument.SaveAs2 FileName:=SaveAsName, FileFormat:=17
    End With

    IDAnchor = ID

            rs.MoveNext
    Loop

    WordApp.Quit savechanges:=wdDoNotSaveChanges
    Set WordApp = Nothing
    Set WordDoc = Nothing
    Set rs = Nothing
    Set db = Nothing

    MsgBox Records & " Forms Created"

End Sub

代碼執行正常,有一個例外,即Word中的查找和替換元素

'   Send commands to Word
    With WordApp
        With WordDoc.Content.Find
            .Text = IDAnchor
            .Replacement.Text = ID
            .Wrap = wdFindContinue
            .Execute Replace:=wdReplaceAll
        End With
        .ActiveDocument.SaveAs2 FileName:=SaveAsName, FileFormat:=17
    End With

更奇怪的是,我有一個通過Excel運行的代碼版本,並且運行完全沒有任何問題,我完全按原樣從該子程序中提取了這部分代碼。 所以這適用於Excel,但不適用於Access,但我不知道為什么。

真的很感激可能提供的任何幫助

非常感謝...

實際上我自己已經弄明白了...我沒有在工具下引用Word對象庫。

總是很簡單!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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