【发布时间】:2019-03-05 23:49:42
【问题描述】:
我一直在努力让它发挥作用。我有一个包含客户信息的 Excel 工作簿。我想单击一个按钮,该按钮运行一个宏,该宏接受一个 word 文档 - 一个模板 - 并根据 Excel 工作簿中存储的数据更新模板中的字段(即我想要“客户端”自定义属性字段在模板将其值更改为“John Smith”)。
我能够很好地打开word文档,并且在从word VBA更新字段方面取得了一些成功,但我无法让excel vba更新word文档的字段。我得到的错误是 4248, ~"no document is open",发生在 for 循环中。如果我将 for 循环放在 OpenWordDoc 中,我仍然会收到 4248 错误。任何帮助表示赞赏。
这是我一直在使用的代码:
Sub GenDraftLetter()
Dim i As Long
Dim j As Double
Dim k As Object
Dim filenam As String
Dim prop As DocumentProperty
Dim oppname As String
Dim clientname As String
Dim objWord As Object
Dim ow As Window
Dim wd As Object
Dim fwd As Object
Set objWord = GetObject(, "Word.Application")
If objWord Is Nothing Then
Set objWord = CreateObject("Word.Application")
End If
i = InputBox("Number of row for the Client", "Row for Client")
j = 1
Do Until Mid(Cells(i, 1), j, 1) = ","
j = j + 1
Loop
clientname = Right(Cells(i, 1), Len(Cells(i, 1)) - j - 1) & " " & Left(Cells(i, 1), j - 1)
filenam = "template.docx"
OpenWordDoc (filenam)
For Each prop In ActiveDocument.CustomDocumentProperties
If LCase(prop.Name) = "client" Then
prop.Value = clientname
Exit For
End If
Next
End Sub
Private Sub OpenWordDoc(filenam)
Dim fullname As String
Dim driv As String
Dim filepat As String
Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open filepat Thisworkbook.Path & "\" & filenam
wordapp.Visible = True
wordapp.Activate
【问题讨论】: