以下代码旨在用Excel中的格式化数据更新Word书签,但是格式化没有涉及到并且不确定为什么,将不胜感激任何建议。格式化的数据是带有某些下划线的文本。
Set wb = ActiveWorkbook
TodayDate = Format(Date, "mmmm d, yyyy")
Path = wb.Path & "\update_file.docx"
'Create a new Word Session
Set pappWord = CreateObject("Word.Application")
'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
docWord.Bookmarks(xlName.Name).Range.Text = Range(xlName).Text
End If
Next xlName
答案 0 :(得分:0)
请改用Copy
和(文档记录不充分的)ExecuteMso
方法。您需要对范围使用Copy
(以捕获格式),然后可以有效地执行与右键单击 Paste + Keep Source Formatting 选项相同的操作:
If docWord.Bookmarks.Exists(xlName.Name) Then
xlName.RefersToRange.Copy
docWord.Bookmarks(xlName.Name).Select
docWord.Application.CommandBars.ExecuteMso "PasteSourceFormatting"
End If
或者,这可能会更好,因为ExecuteMso
是异步的,并且可能导致计时问题:
xlName.RefersToRange.Copy
docWord.Bookmarks(xlName.Name).Range.PasteAndFormat 16 'wdFormatOriginalFormatting