【发布时间】:2020-04-03 08:45:45
【问题描述】:
我正在编写将数据从 Access 表单(在将表单保存到表中之前)传递到 Word 文档中的书签的 VBA 代码。
它运行良好,但用户可能会在保存 Word 文档之前对其进行编辑,因此我需要代码将数据从 Word 书签返回到 Access 表单(之前打开过)。假设我只是将一个书签数据传递给表单中的一个字段,我需要清除该字段然后将数据传递给它。
我看到了一些从 Word 传递到 Access 表的方法,但我正在寻找传递到表单的方法。
以下从 Access 传递到 Word 的代码运行良好:
Private Sub Command68_Click()
Call fillWordForm
End Sub
Function fillWordForm()
Dim appWord As Object
Dim doc As Object
Dim path As String
Dim myID As String
On Error Resume Next
Error.Clear
Set appWord = CreateObject("word.application")
If Err.Number <> 0 Then
Set appWord = New Word.Application
appWord.Visible = True
End If
path = Application.CurrentProject.path & "\H_F.docx"
If FileExists(path) = False Then
MsgBox "Template File Not Found", vbExclamation, "File Not Found"
Else
Set doc = appWord.Documents.Add(path, , True)
myID = DLookup("ID", "Exports_imports_Table", "[ID] = " & Me.ID)
With doc
.FormFields("BookID").Result = [ID]
.FormFields("Book_BC_date").Result = Me.date_BC
.FormFields("Book_AH_date").Result = Me.date_AH
.FormFields("Book_AH_date").Result = Me.date_AH
.FormFields("BookTopic").Result = Me.topic
.FormFields("BookProjectName").Result = Me.projectName
.FormFields("BookCompanyName").Result = Me.companyName
.FormFields("BookContent").Range.Text = Me.content
'Result = Me.content
appWord.Visible = True
appWord.Active
End With
Set doc = Nothing
Set appWord = Nothing
End If
End Function
Function FileExists(ByVal strFile As String, Optional bFindFolders As Boolean) As Boolean
'Purpose: Return True if the file exists, even if it is hidden.
'Arguments: strFile: File name to look for. Current directory searched if no path included.
' bFindFolders. If strFile is a folder, FileExists() returns False unless this argument is True.
'Note: Does not look inside subdirectories for the file.
'Author: Allen Browne. http://allenbrowne.com June, 2006.
Dim lngAttributes As Long
'Include read-only files, hidden files, system files.
lngAttributes = (vbReadOnly Or vbHidden Or vbSystem)
If bFindFolders Then
lngAttributes = (lngAttributes Or vbDirectory) 'Include folders as well.
Else
'Strip any trailing slash, so Dir does not look inside the folder.
Do While Right$(strFile, 1) = "\"
strFile = Left$(strFile, Len(strFile) - 1)
Loop
End If
'If Dir() returns something, the file exists.
On Error Resume Next
FileExists = (Len(Dir(strFile, lngAttributes)) > 0)
End Function
【问题讨论】:
-
您希望 Access VBA 打开 Word 文档并填写书签,允许用户编辑这些数据,然后 Access 代码将这些编辑拉回表单 - 所有这些都在一个会话中完成?我怀疑它可以做到。 Word 文档打开时访问过程不会暂停执行。如何暂停以允许用户编辑然后恢复检索输入?用户应该对 Access 表单进行所有输入,然后仅在对条目感到满意时才打开 Word 文档。
-
@June7 感谢您的回复,而不是在一个会话中,例如,如果我单击 word 上的按钮或保存 word 文档,则将执行传输事件(只需清除访问中的字段表单并将数据传递给它)
-
那么您需要 Word 模板文档背后的代码来自动化 Access,然而,这意味着 Word VBA 必须打开与已经打开的 Access 文件的连接。不知道这是否可能。我希望有 Word VBA 的示例来自动化 Access。您需要尝试代码,当您遇到特定问题时,发布问题。似乎是一个不必要的复杂过程。为什么要这样做?