将表格从Excel复制到Word VBA

时间:2018-08-17 09:08:58

标签: excel vba ms-word word-vba

我正在尝试获取Word文档并填充占位符,但使用FindReplaceAll方法(效果很好),然后将表格从excel复制到Word文档中-目的是找到表格的占位符,然后替换它,但我无法将表格放到正确的位置(替换占位符)。

这是我的代码:

Sub Test()
Dim i As Long, iManager As Long, iFunds As Long
Dim sM As String
Dim WS As Worksheet, WS1 As Worksheet
Dim sManager() As String
Dim objWord

Set objWord = CreateObject("Word.Application")
objWord.Visible = True

Set WS = ThisWorkbook.Sheets("Investment Manager details")
Set WS1 = ThisWorkbook.Sheets("Fund details")
Set WS2 = ThisWorkbook.Sheets("Worksheet")

ReDim sManager(1 To (WS.Range("A" & WS.Rows.Count).End(xlUp).Row - 1), 1 To 2)

For iManager = 1 To UBound(sManager)
    sM = iManager
    sManager(iManager, 1) = WS.Range("A" & iManager + 1).Value
    sManager(iManager, 2) = WS.Range("B" & iManager + 1).Value
    iFunds = WorksheetFunction.CountIf(WS1.Range("H:H"), sManager(iManager, 1))
    objWord.Documents.Open "C:\Users\Jeremy\Documents\Manager Documents\Template.doc"
    With objWord.ActiveDocument.Content.Find
      .Text = "%Manager.Name%"
      .Replacement.Text = sManager(iManager, 1)
      .Replacement.ClearFormatting
      .Replacement.Font.Italic = False
      .Forward = True
      .Wrap = wdFindContinue
      .Format = False
      .MatchCase = False
      .MatchWholeWord = False
      .MatchWildcards = False
      .MatchSoundsLike = False
      .MatchAllWordForms = False
      .Execute Replace:=wdReplaceAll
    End With
    WS1.Range("C50:D52").Copy                                                       'This is just for example - the actual table will vary in size so can be included in the template
    objWord.Selection.GoTo What:=wdGoToBookmark, Name:="Table"
    objWord.Selection.PasteExcelTable False, False, False                           
Next
iManager = 0


objWord.Quit
Set objWord = Nothing

End Sub

如何获取占位符并将粘贴的表放在正确的位置?

1 个答案:

答案 0 :(得分:0)

替换:

bjWord.Selection.GoTo What:=wdGoToBookmark, Name:="Table"
objWord.Selection.PasteExcelTable False, False, False

具有:

objWord.ActiveDocument.Bookmarks("Table").Range.PasteExcelTable False, False, False

无需“选择”任何内容。