我对Access来说还比较陌生,但是我本周一直试图整理一个包裹,以便向我们的员工发出信件。
流程如下: 在Access上填写的表单>保存到表中的数据>合并到Word模板中的相关字段
我似乎在将数据转置到Word的VBA代码中遇到了一些问题。我在网上找到了此代码,尽管它可以正常工作,但仅在其他时间有效。我已经尝试过切掉部分,但到目前为止还没有成功。 始终如一在其他情况下始终有效的方式似乎有些奇怪。我在网上找到了很多关于这种现象的参考,但是它们通常与Excel有关,但是我还没有找到一种可行的解决方案。下面包含的代码仅供参考。
在此先感谢任何可以阐明这一点的人。
乔
Private Sub Command280_Click()
'Print customer slip for current customer.
Dim appWord As Word.Application
Dim doc As Word.Document
'Avoid error 429, when Word isn't open.
On Error Resume Next
Err.Clear
'Set appWord object variable to running instance of Word.
Set appWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
'If Word isn't open, create a new instance of Word.
Set appWord = CreateObject("Word.Application")
End If
Set doc = appWord.Documents.Open("filepath-to-document.docx", , True)
With doc
.FormFields("txtFirstName").Result = Me![First Name]
.FormFields("txtFirstName2").Result = Me![First Name]
.FormFields("txtLastName").Result = Me![Last Name]
.FormFields("txtReasonforReward").Result = Me![Reason for Reward]
.FormFields("txtCompanyValue").Result = Me![Company Value]
.FormFields("txtRequestingManager").Result = Me![Requesting Manager]
.FormFields("txtLocation").Result = Me![Location]
.Visible = True
.Activate
End With
Set doc = Nothing
Set appWord = Nothing
Exit Sub
errHandler:
MsgBox Err.Number & ": " & Err.Description
End Sub
作为对某些评论的回应,我将代码修改如下,但是此代码没有任何错误管理,并导致文档在Web view(?)中打开:
Private Sub Command280_Click()
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set doc = objWord.Documents.Add("FilePath.docx", , True)
With doc
.FormFields("txtFirstName").Result = Me![First Name]
.FormFields("txtFirstName2").Result = Me![First Name]
.FormFields("txtLastName").Result = Me![Last Name]
.FormFields("txtReasonforReward").Result = Me![Reason for Reward]
.FormFields("txtCompanyValue").Result = Me![Company Value]
.FormFields("txtRequestingManager").Result = Me![Requesting Manager]
.FormFields("txtLocation").Result = Me![Location]
.Visible = True
.Activate
End With
End Sub