Ste*_*Dea 5 ms-access vba replace ms-word find
我已经成功地在 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
Run Code Online (Sandbox Code Playgroud)
代码执行得很好,只有一个例外是 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
Run Code Online (Sandbox Code Playgroud)
更奇怪的是,我有一个通过 Excel 运行的代码版本,它运行时没有任何问题,而且我已经完全按原样从该子例程中提取了这部分代码。所以这在 Excel 中有效,但在 Access 中无效,但我不知道为什么。
非常感谢可能提供的任何帮助
非常感谢...
| 归档时间: |
|
| 查看次数: |
4216 次 |
| 最近记录: |