使用书签将excel单元格(例如A1:C10)复制到Word文档而不删除书签

时间:2016-03-07 21:23:52

标签: excel vba ms-word bookmarks

我试过找到解决方案,但收效甚微。我成功地能够更新我的Word文档但只能更新一次。我检查了word文档并且书签已经消失,因此第二次不起作用,除非我在Word文档中再次添加书签。请找到下面的代码,让我知道可以做些什么来达到要求。谢谢!

Sub Rectangle2_Click()
Dim tbl As Excel.Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table

'Optimize Code
 Application.ScreenUpdating = False
 Application.EnableEvents = False

'Copy Range from Excel
 Set tbl = ThisWorkbook.Worksheets("Sheet1").Range("C6:M10")

'Create an Instance of MS Word
 On Error Resume Next

'Is MS Word already opened?
  Set WordApp = GetObject(class:="Word.Application")

'Clear the error between errors
  Err.Clear

'If MS Word is not already open then open MS Word
  If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")

'Handle if the Word Application is not found
  If Err.Number = 429 Then
    MsgBox "Microsoft Word could not be found, aborting."
    GoTo EndRoutine
  End If

 On Error GoTo 0

'Make MS Word Visible and Active
 WordApp.Visible = True
 WordApp.Activate

'Open the Report
 Set myDoc = WordApp.Documents.Open("C:\Users\Test.docx")

'Copy Excel Table Range
 tbl.Copy

'Delete old Table in MS Word & Paste New Table into MS Word
 Dim bkm As Bookmark
 For Each bkm In ActiveDocument.Bookmarks
    If bkm.Name = bkmname Then
        If bkm.Range.Information(wdWithInTable) = True Then
            bkm.Range.Expand (wdCell)
            bkm.Range.Cells.Delete
        End If
    End If
 Next bkm

myDoc.Bookmarks(1).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False

'Autofit Table so it fits inside Word Document
 Set WordTable = myDoc.Tables(1)
 WordTable.AutoFitBehavior (wdAutoFitWindow)

 EndRoutine:
'Optimize Code
 Application.ScreenUpdating = True
 Application.EnableEvents = True

'Clear The Clipboard
 Application.CutCopyMode = False

'Closing the MS Word
 ActiveDocument.Close SaveChanges:=wdSaveChanges
 End Sub

注意:我是第一次纯粹使用VBA,但已经从不同来源拼凑出来,希望记住正确的逻辑

1 个答案:

答案 0 :(得分:0)

有一种方法可以重复使用书签,但如果我正确理解您正在做的事情,那么创建模板文件(.dotx)并生成 new 每次迭代的文档。

您的代码应该是

Set myDoc = Documents.Add("template path") 

并使用Document.SaveAs方法保存每个文档。

书签将保持不变,因为您的代码始终使用从模板创建的新文档。

附加说明:由于您要声明对象(myDoc)而不是使用ActiveDocument!这将使您的代码更加健壮,因为用户或其他代码可以更改Word UI中当前处于活动状态的文档。所以,例如:

For Each bkm In myDoc.Bookmarks

如果您需要保留书签,执行此操作的方法是首先保存书签范围,将内容分配给书签(删除书签),然后围绕范围恢复书签。类似的东西:

Dim rngBkm as Word.Range
For Each bkm In myDoc.Bookmarks
  If bkm.Name = bkmname Then
    Set rngBkm = bkm.Range
    rngBkm.Text = "new content"
    myDoc.Bookmarks.Add(rngBkm, bkmname)
  End If
Next