使用 VBA Excel 将光标移动到 Word 文档的末尾

问题描述 投票:0回答:2

在使用 VBA Excel 将多个 Word 文档合并为一个大文档中。我正在打开一个Word模板,并想在模板文档的末尾添加其他Word文档的内容。 打开模板后,我将另一个Word文档的内容复制到剪贴板,他们想将剪贴板内容粘贴到模板的末尾。 粘贴命令后,完整的模板内容将被剪贴板内容替换。

Sub ModulesSamenvoegen()
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Dim PadnaamNaarHandleidingen As String
Dim RegelCounter As Integer
Dim ModuleCounter As Integer
Dim TekstModule As Word.Document
Dim Template As String
Dim Taal As String
Dim blnStart As Boolean
Dim ModuleRange As Range


Template = PadnaamNaarHandleidingen & "\" & Taal & "\Templates\" & "Masterhandleiding " & Taal & ".dotx"

'Open Word template

On Error Resume Next
'Kijk of Word al draait
Set WordApp = GetObject(Class:="Word.Application")
If WordApp Is Nothing Then
' Start Word
    Set WordApp = CreateObject(Class:="Word.Application")
    If WordApp Is Nothing Then
        MsgBox "Het is niet gelukt Word te starten!", vbExclamation
        Exit Sub
    End If
    blnStart = True
End If
On Error GoTo ErrHandler
WordApp.Visible = True
WordApp.Activate
WordApp.WindowState = wdWindowStateMaximize

'Open document
Set WordDoc = WordApp.Documents.Open(FileName:=Template)
WordApp.Selection.EndKey

'Voeg alle module uit array samen
ModuleCounter = 1
For RegelCounter = 1 To AantalTekstModules
    Set TekstModule = WordApp.Documents.Open(FileName:=PadnaamNaarHandleidingen & "\" & Taal &     "\Tekstmodules\" & ModuleNaam(ModuleCounter))
    TekstModule.Select
    TekstModule.Range.Copy
    TekstModule.Close
    WordDoc.Select
    
    WordDoc.Range.Paste

    ModuleCounter = ModuleCounter + 1
Next

'Sluit en bewaar het document
WordDoc.Close SaveChanges:=True

ExitHandler:
On Error Resume Next
If blnStart Then
'Als we Word hadden gestart, sluiten we het nu weer
    WordApp.Quit SaveChanges:=False
End If
Exit Sub

ErrHandler:
    MsgBox Err.Description, vbExclamation
    Resume ExitHandler
End Sub
excel vba import ms-word
2个回答
0
投票

用此替换您的选择/复制/粘贴代码

WordDoc.Paragraphs.Last.Range.InsertAfter TekstModule.Content

这仅复制文本,不复制图像等。


0
投票
  • WordApp.Selection.EndKey
    不会将插入点移动到文档末尾。参数
    Unit
    的默认值为
    wdLine
    。应该是
    WordApp.Selection.EndKey wdStory
  • TekstModule.Content.Copy
    复制文档的内容(包括形状)。

微软文档:

文档.内容属性(Word)

Selection.EndKey 方法(Word)

'Voeg alle module uit array samen
ModuleCounter = 1
For RegelCounter = 1 To AantalTekstModules
    Set TekstModule = WordApp.Documents.Open(FileName:=PadnaamNaarHandleidingen & "\" & Taal &     "\Tekstmodules\" & ModuleNaam(ModuleCounter))
    TekstModule.Content.Copy ' copy it w/o select
    WordDoc.Activate
    WordApp.Selection.EndKey wdStory
    WordApp.Selection.TypeParagraph ' paste at the new paragraph
    WordApp.Selection.Paste
    TekstModule.Close ' close doc after paste
    ModuleCounter = ModuleCounter + 1
Next
© www.soinside.com 2019 - 2024. All rights reserved.