【发布时间】:2015-07-13 02:52:18
【问题描述】:
我正在处理一个调用 Word 文档模板并更新/替换特定封闭书签中的所有文本而不删除实际书签的 Excel 文件。保留 Word 中的书签括号非常重要,因为存在依赖这些书签保持完整的交叉引用,否则它们将不起作用。我在这里和其他一些论坛梳理了一些不同的帖子,但经过大约 4 小时的反复试验,我似乎无法让它工作。
我在运行宏时遇到的最新错误是“错误编号:13”这是代码 - 谁能帮我弄清楚我在搞什么鬼?使用以下建议可以让我大部分时间到达那里,但是当我将 BMRange 设置为书签时,我得到错误 13 - http://word.mvps.org/faqs/macrosvba/InsertingTextAtBookmark.htm
ub BCMerge()
Dim pappWord As Object
Dim docWord As Object
Dim wb As Excel.Workbook
Dim xlName As Excel.Name
Dim TodayDate As String
Dim Path As String
Dim BMRange As Range
Set wb = ActiveWorkbook
TodayDate = Format(Date, "mmmm d, yyyy")
Path = wb.Path & "\pushmerge1.dot"
On Error GoTo ErrorHandler
'Create a new Word Session
Set pappWord = CreateObject("Word.Application")
On Error GoTo ErrorHandler
'Open document in word
Set docWord = pappWord.Documents.Add(Path)
'Loop through names in the activeworkbook
For Each xlName In wb.Names
'if xlName's name is existing in document then put the value in place of the bookmark
If docWord.Bookmarks.Exists(xlName.Name) Then
'Identify current Bookmark range and insert text
Set BMRange = docWord.Bookmarks(xlName.Name).Range '''Mismatch Error 13'''
BMRange.Text = Range(xlName.Value)
'Re-insert the bookmark
docWord.Bookmarks.Add xlName.Name, BMRange
End If
Next xlName
'Activate word and display document
With pappWord
.Visible = True
.ActiveWindow.WindowState = 0
.Activate
End With
'Release the Word object to save memory and exit macro
ErrorExit:
Set pappWord = Nothing
Exit Sub
'Error Handling routine
ErrorHandler:
If Err Then
MsgBox "Error No: " & Err.Number & "; There is a problem"
If Not pappWord Is Nothing Then
pappWord.Quit False
End If
Resume ErrorExit
End If
End Sub
【问题讨论】:
标签: excel vba ms-word bookmarks