我已将.docm作为模板。
在模板中有一个宏,它将表单字段复制到Access数据库。
当我直接在.docm文件中运行宏时,不会创建错误。
当我按预期通过Access运行宏时,会显示错误:
无效的SQL语句;预期'删除' INSERT''程序' SELECT' SELECT'或者'更新'。
我的.docm代码可以在这里找到:
Private Sub CommandButton1_Click()
Dim appWord As Word.Application
Dim doc As Word.Document
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim strDocName As String
Dim blnQuitWord As Boolean
On Error GoTo ErrorHandling
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=F:\app\test.accdb"
rst.Open "Table1", cnn, _
adOpenKeyset, adLockOptimistic
With rst
.AddNew
!Field1 = ActiveDocument.FormFields("Text1").Result
!Field2 = ActiveDocument.FormFields("Text1").Result
!Field3 = ActiveDocument.FormFields("Text1").Result
.Update
.Close
End With
'doc.Close
If blnQuitWord Then appWord.Quit
cnn.Close
MsgBox "Data Imported!"
Cleanup:
Set rst = Nothing
Set cnn = Nothing
Set doc = Nothing
Set appWord = Nothing
Exit Sub
ErrorHandling:
Select Case Err
Case -2147022986, 429
Set appWord = CreateObject("Word.Application")
blnQuitWord = True
Resume Next
Case 5121, 5174
MsgBox "You must select a valid Word document. " _
& "No data imported.", vbOKOnly, _
"Document Not Found"
Case 5941
MsgBox "The document you selected does not " _
& "contain the required form fields. " _
& "No data imported.", vbOKOnly, _
"Fields Not Found"
Case Else
MsgBox Err & ": " & Err.Description
End Select
GoTo Cleanup
End Sub
我的访问VBA:
file = FileSelected
Dim wordApp As Object
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = True
wordApp.Documents.Open FileName:=file
wordApp.Run "Insert_data"
wordApp.Documents.Close True
wordApp.Quit
有什么必须改变,让它运行!?
编辑:我添加了所需的库