将整个故事从Word复制并粘贴到Excel

时间:2017-12-29 21:01:57

标签: excel-vba vba excel

我有一个定期收到的Word文档,需要与Excel中已有的其他数据结合使用,作为更大输出的一部分。我可以将整个文档(WholeStory)从Word复制并粘贴到Excel中,但我想将这部分作为整个Excel输出宏。我目前的这部分代码如下,除了没有粘贴外,它的工作正常。当它到达那里时没有数据要粘贴,所以我想它要么不是开始使用它,要么不进行重复操作。寻求这方面的帮助。非常感谢!

Sub ImportSectHWord()

Dim objWord As Object
Dim objDoc As Object
Dim wdFileName

Set objWord = CreateObject("word.Application")
wdFileName = Application.GetOpenFilename("Word Documents, *.doc*")

If wdFileName = False Then Exit Sub

Set objDoc = GetObject(wdFileName)

objWord.Documents.Open (wdFileName)
objWord.Selection.WholeStory
Selection.Copy

Worksheets("H Import").Select
Range("A1").Select
ActiveSheet.Paste

objDoc.Close SaveChanges:=wdDoNotSaveChanges
objWord.Quit

End Sub

1 个答案:

答案 0 :(得分:2)

声明

Selection.Copy

正在复制Excel中当前选择的任何内容。

要复制Word中的Selection对象,请使用

objWord.Selection.Copy

总是建议在使用方法和属性时限定您引用的对象,即使VBA提供默认对象也是如此。

Sub ImportSectHWord()
    'It is better to always define constants, even though they will default to zero
    ' which just happens to be the desired value in this case
    Const wdDoNotSaveChanges As Long = 0

    Dim objWord As Object
    Dim objDoc As Object
    Dim wdFileName

    Set objWord = CreateObject("word.Application")
    wdFileName = Application.GetOpenFilename("Word Documents, *.doc*")

    If wdFileName = False Then Exit Sub

    Set objDoc = GetObject(wdFileName)

    objWord.Documents.Open (wdFileName)
    objWord.Selection.WholeStory
    objWord.Selection.Copy

    ActiveWorkbook.Worksheets("H Import").Select
    ActiveWorkbook.Worksheets("H Import").Range("A1").Select
    ActiveWorkbook.ActiveSheet.Paste

    objDoc.Close SaveChanges:=wdDoNotSaveChanges
    objWord.Quit

End Sub