我正在尝试使用VBA将Excel用户窗体中的字符串传递给Word文档。在Word文档中,我创建了一个field> doc变量并将其命名为bookingRef
。代码如下:
Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
Set doc = objWord.Documents.Open("test.docx")
objWord.ActiveDocument.variables("bookingRef").Value = Me.txtRef.Text
objWord.ActiveDocument.Fields.Update
objWord.Documents.Save
它没有任何错误,但是当我打开文档时,我必须右键单击并更新字段(我以为objWord.ActiveDocument.Fields.Update
是这样做的吗?)。而且,它会一直锁定文档,因此无法再次打开它。保存后是否可以解锁?
答案 0 :(得分:1)
该文档被锁定,因为您没有使用Document.Close method将其关闭,因此该文档仍处于打开状态,因此无法再次打开。
还要避免使用ActiveDocument
所打开的文档被设置为doc
Set doc = objWord.Documents.Open("test.docx")
,因此可以用doc.
Dim objWord As New Word.Application
Dim doc As Word.Document
'Dim bkmk As Word.Bookmark
Set doc = objWord.Documents.Open("test.docx")
doc.variables("bookingRef").Value = Me.txtRef.Text
doc.Fields.Update
doc.Save
doc.Close
完成后,请不要忘记退出Word应用程序。
objWord.Quit
否则,Word的实例将一直打开,直到您关闭计算机。
Fields.Update method应该更新字段,但是由于错误而可能不成功。检查是否存在错误:
If doc.Fields.Update = 0 Then
MsgBox "Update Successful"
Else
MsgBox "Field " & doc.Fields.Update & " has an error"
End If
(遵循How to store and retrieve variables in Word documents的步骤)
创建了文件C:\Temp\test.docx
要使用DocVariable
字段,请按照以下步骤操作:
在Insert
菜单上,单击Field
。
Document Automation
。Field names
列表中,选择DocVariable
。New Name
框的Field properties
下,键入文档变量bookingRef
的名称。单击“确定”。
请注意,您将在文档中看不到任何内容,但是没关系,因为变量bookingRef
还不存在。
保存文件并关闭Word。
在Excel中运行以下代码
Option Explicit
Public Sub Test()
Dim objWord As New Word.Application
On Error GoTo CLOSE_WORD_APP 'error handling to ensure there will not be any orphaned and invisible Word application left
Dim doc As Word.Document
Set doc = objWord.Documents.Open("C:\Temp\test.docx")
doc.Variables("bookingRef").Value = "This is the updated Value: " & Time
doc.Fields.Update
doc.Save
doc.Close
CLOSE_WORD_APP:
objWord.Quit SaveChanges:=False
If Err.Number <> 0 Then
Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
End If
End Sub
打开Word文档C:\Temp\test.docx
,看看一切都已更新: