首页 > 解决方案 > 在word中的特定文本之后添加excel范围

问题描述

在 excel 中,我想使用宏将单元格范围复制到现有 word 文档中的特定位置。该位置应该在该 word 文档中的唯一单词之后。

这是 2 个文件:https ://1drv.ms/u/s!AoL8lLA69BSAiu0z6xdsvRK7IzyC9A?e= R8E5ex(带有和不带宏的 excelsheet)

这是excel宏:

Sub test()
'
' test Macro
'
' Sneltoets: Ctrl+Shift+P


Worksheets("artikelen").Range("A2:I6").Copy


Dim wdapp As Object, wddoc As Object
Dim strdocname As String

On Error Resume Next
Set wdapp = GetObject(, "Word.Application")
If Err.Number = 429 Then
    Err.Clear
    Set wdapp = CreateObject("Word.Application")
End If
wdapp.Visible = True
strdocname = "C:\temp\test1.docx"
If Dir(strdocname) = "" Then
    MsgBox "The document " & strdocname & vdCrLf & " is not found at the defined location.", vbExclamation
    Exit Sub
End If

wdapp.Activate

If wddoc Is Nothing Then
    Set wddoc = wdapp.Documents.Open(strdocname)
End If


Set myRange2 = wddoc.Content
myRange2.Find.Execute FindText:="searchtext"
wddoc.Range.Paste



wddoc.Save
' wdapp.Quit

Set wddoc = Nothing
Set wdapp = Nothing
Application.CutCopyMode = False

End Sub

++++++++

唯一不起作用的是在我的word-doc中的单词:'searchtext'之后粘贴excel范围。这是一段代码:

Set myRange2 = wddoc.Content
    myRange2.Find.Execute FindText:="searchtext"
    wddoc.Range.Paste

...那不工作

我觉得我有 99% 在那里......任何帮助将不胜感激。提前致谢。rgrds,理查德

标签: excelvbams-wordrangepaste

解决方案


您的代码几乎是正确的。

wddoc.Range当您将整个文档粘贴到其中时,粘贴无法正常工作。您应该粘贴到myRange2中,但前提是找到您要搜索的文本。

幸运的是,成功的查找将设置myRange2为找到的文本的范围。如下更改您的代码应该使粘贴适合您:

  If myRange2.Find.Execute(FindText:="searchtext") Then
    myRange2.Collapse wdCollapseEnd
    myRange2.Paste
  End If

推荐阅读