首页 > 解决方案 > 将已添加书签的部分从 Word 导入 Excel

问题描述

嗨,我正在尝试使用 VBA(在 Excel 中)将一个带书签的部分(开头的书签命名为“开始”,结尾的书签命名为“结束”)形成一个 Word 文档到 Excel 工作表。

我尝试了以下代码,但它不起作用。我的范围描述有误:

rngDoc = .Range(Start:=.Bookmarks("Start").Range.Start, End:=.Bookmarks("End").Range.End))

它告诉我它在集合中找不到以下元素(翻译自德语“Das aufgeforderte Element ist nicht in der Sammlung vorhanden”)。有人知道如何描述范围吗?

Sub ImportPartAHoftorbilanz()

Dim wdDoc As Word.Document
Dim wdFileName As Variant
Dim rngStart As Range
Dim rngEnd As Range


'Get Wordfile and Open It
wdFileName = Application.GetOpenFilename("Word files (*.docx),*.docx", , _
"Browse for file containing table to be imported")
If wdFileName = False Then Exit Sub '(user cancelled import file browser)
Set wdDoc = GetObject(wdFileName) 'open Word file

With wdDoc
    Dim rngDoc As Object
    rngDoc = .Range(Start:=.Bookmarks("Start").Range.Start, End:=.Bookmarks("End").Range.End)
    rngDoc.Copy SaveChanges:=False
End With

'Paste Selection
Range("A1").PasteSpecial Paste:=xlPasteValues

Set wdDoc = Nothing
End Sub

标签: excelvbaimportms-word

解决方案


从“With wdDoc”语句开始,将剩余代码更改为以下内容:

With wdDoc
    Dim rngDoc As word.Range
    Set rngDoc = .Range(Start:=.Bookmarks("Start").Range.Start, End:=.Bookmarks("End").Range.End)
    rngDoc.Copy
End With

'Paste Selection
Range("A1").PasteSpecial Paste:=xlPasteValues

wdDoc.Close SaveChanges:=False
Set wdDoc = Nothing

推荐阅读