简体   繁体   中英

Excel VBA copy and paste selected text from word

I want a macro button on my Excel sheet that:

  1. I will highlight (select) some text in a word document

  2. I press the button

  3. the text is then copied and pasted into a specified cell in my excel sheet

I have tried:

sub paste()
    objword.selection.copy range("B2")
End sub

Firstly I don't know whether objword is the right syntax, and secondly everytime I select text in word, I cannot click on excel without the text deselecting, so how will I be able to do this? Do I have to create the macro in word?

Thanks

The following code (requiring a reference to Microsoft Word xx Object Library) running in Excel will grab the current selection in Word and copy the text into A1:

Sub paste()
    Dim oWd As Word.Application
    Set oWd = GetObject(, "Word.Application")
    ActiveSheet.Cells(1, 1) = oWd.Selection
    Set oWd = Nothing
End Sub

Also, the following is the equivalent opposite, ie code that can run in Word that takes the selection in Word and sends it to Excel:

Sub paste()
    Dim oXL As Excel.Application
    Set oXL = GetObject(, "Excel.Application")
    oXL.ActiveSheet.Cells(1, 1) = Selection.Text
    Set oXL = Nothing
End Sub

This one requires a reference to Microsoft Excel xx Object Library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM