2017-03-15 181 views
3

我已经成功地在Excel中编写了一些打开现有Word文档的VBA代码,根据Excel工作表中的信息找到并替换了一个字符串。VBA访问 - 在Word文档中查找和替换文本

由于源数据来自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中,但我不知道为什么。

会很感激的任何帮助,可能是可用的

非常感谢......

回答

2

其实我只是理解了它自己...我还没有提及下工具Word对象库。

总是很简单!

相关问题