VBA Access-查找和替换Word文档中的文本

VBA Access-查找和替换Word文档中的文本,vba,ms-access,replace,ms-word,find,Vba,Ms Access,Replace,Ms Word,Find,我已经成功地在Excel中编写了一些VBA代码,它可以打开现有的Word文档,根据Excel工作表中的信息查找并替换字符串 由于源数据来自Access数据库,我想我会尝试将VBA代码移动到Access中,然后从那里运行它 更新后的代码大部分工作正常,但奇怪的是,当我在access中运行它时,查找和替换文本字符串的代码部分不工作 Sub CreateFormsPDF() ' Creates Garda Vetting Forms NVB1 in Word and saves as PDF

我已经成功地在Excel中编写了一些VBA代码,它可以打开现有的Word文档,根据Excel工作表中的信息查找并替换字符串

由于源数据来自Access数据库,我想我会尝试将VBA代码移动到Access中,然后从那里运行它

更新后的代码大部分工作正常,但奇怪的是,当我在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中的Find和Replace元素,即

'   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中无效,但我不知道为什么

非常感谢任何可能提供的帮助


非常感谢…

事实上,我自己刚刚弄明白了…我没有引用工具下的单词对象库

总是简单的事情