在word中的特定文本后添加excel范围



在excel中,我想使用宏将单元格范围复制到兴奋词文档中的特定位置。该位置应位于该单词文档中唯一单词的正后方。

以下是两个文件:https://1drv.ms/u/s!AoL8lLA69BSAiu0z6xdsvRK7IzyC9A?e=R8E5ex(带和不带宏的除外(

这是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:temptest1.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文档中的单词"searchtext"后面粘贴excel范围。这是一段代码:

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

不起作用

我觉得我99%都在那里。。。任何帮助都将不胜感激。提前谢谢。rgrds,Richard

您的代码几乎是正确的。

粘贴到wddoc.Range(整个文档(时,粘贴操作不正常。您应该粘贴到myRange2中,但前提是找到了要搜索的文本。

幸运的是,一个成功的查找将把myRange2设置为查找到的文本的范围。按照以下方式更改您的代码应该可以使粘贴为您工作:

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

最新更新