Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

vba - Copy and paste Whole Story from Word to Excel

I have a Word document that is received periodically that needs to be combined with other data already in Excel as part of a larger output. I can copy and paste the whole document (WholeStory) from Word into Excel, but I want to make this part of the whole Excel output macro. My current code for this portion is below, and it works fine except that it pastes nothing. There is no data to paste when it gets there, so I guess it is either not picking it up to start with or not carrying it over. Looking for assistance with this. Thanks very much!

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The statement

Selection.Copy

is copying whatever is currently selected in Excel.

To copy the Selection object in Word, use

objWord.Selection.Copy

It is always advisable to qualify what objects you are referring to when using methods and properties, even when VBA provides a default object.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...