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

5
我已成功在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中的查找和替换元素,即:

'   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中却不行,但我不知道原因。

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

非常感谢...

1个回答

3

实际上,我刚刚自己找到了答案...我没有在工具中引用Word对象库。

总是有些简单的问题!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接