简体   繁体   English

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

[英]Copying excel cells (ex. A1:C10) to word document using bookmarks without deleting the bookmarks

I have tried finding a solution to this but with little succes.我试图找到解决方案,但收效甚微。 I was succesfully able to update my Word Document but only once.我成功地更新了我的 Word 文档,但只有一次。 I checked the word document and the bookmark has disappeared so doesn't work the second time unless I add a bookmark again in the Word Document.我检查了 word 文档,书签已经消失,所以第二次不起作用,除非我在 Word 文档中再次添加书签。 Please find the code below and let me know what may be done to achieve the required.请找到下面的代码,让我知道可以做些什么来实现所需的。 Thanks!!谢谢!!

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

NOTE : I am purely using VBA for the first time but have pieced this up from different sources with hopefully the right logic in mind注意:我是第一次纯粹使用 VBA,但已经从不同的来源拼凑起来,希望能记住正确的逻辑

There is a way to re-use bookmarks, but if I correctly understand what you're doing it would be much better for you to create a template file (.dotx) and generate a new document from it for each iteration.有一种方法可以重用书签,但如果我正确理解您在做什么,那么您最好为每次迭代创建一个模板文件 (.dotx) 并从中生成一个文档。

Your code should then be你的代码应该是

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

and you save each document using the Document.SaveAs method.并使用Document.SaveAs方法保存每个文档。

The bookmarks will remain intact since your code always works with a fresh document created from the template.书签将保持不变,因为您的代码始终与从模板创建的新文档一起使用。

Additional note: Since you're declaring an object (myDoc) use that instead of ActiveDocument!附加说明:由于您要声明一个对象 (myDoc),请使用它而不是 ActiveDocument! This will make your code more robust, since the user or other code could change which document is currently active in the Word UI.这将使您的代码更加健壮,因为用户或其他代码可能会更改 Word UI 中当前处于活动状态的文档。 So, for example:因此,例如:

For Each bkm In myDoc.Bookmarks

In case you need to retain bookmarks, the way to do this is to first save the bookmark Range, assign the content to the bookmark (which deletes it), then restore the bookmark around the range.如果您需要保留书签,这样做的方法是首先保存书签范围,将内容分配给书签(删除它),然后恢复范围周围的书签。 Something like:就像是:

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    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM