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

标签 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
    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

代码执行良好,但有一个异常(exception),即 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对象库。

总是简单的事情!

关于VBA Access - 在 Word 文档中查找和替换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42814790/

相关文章:

excel - XPath 在带有 DOMDocument 的 Excel VBA 中无法正常工作

ms-access - OleDbCommand 无法执行此命令,为什么?

c# - 如何在执行或设置时将 visual studio 中的文件路径修改为我的数据库

r - 如何用查找表中的值标签替换数字代码?

javascript - 在javascript中每次替换时增加一个数字

excel - VSTO COM 插件 ProgID

Vba:显示带点而不是逗号的小数

excel - VBA中的简单递归函数,Excel不返回预期结果

excel - FileDialog(msoFileDialogFolderPicker) - 如何将初始路径设置为 "root"/ "This PC"?

javascript - 使用javascript,如何使字符串仅包含字母、数字和句点。删除所有其他字符