简体   繁体   中英

How to switch to open Excel spreadsheet and work on it from Word with VBA

I'm just trying to work on an open Excel spreadsheet from Word using VBA. I did a search on this and found the following code on How to get reference to an open Excel spreadsheet from Word? . The problem is, it seems to open a separate instance of Excel rather than the one I already have open, and then closes it after the action. How can I get the procedure to switch to the open Excel spreadsheet, perform the desired actions, and leave the spreadsheet open?

   Sub DoStuffWithExcelInWord()
       Dim xl As Excel.Application
       Dim wkbk As Excel.Workbook
       Dim wk As Excel.Worksheet
       Set xl = CreateObject("Excel.Application")
       Set wkbk = xl.Workbooks.Open("C:\test.csv")
       Set wk = wkbk.Sheets(1)

       Debug.Print wk.Cells(1, 1).Value 'Here's where I would like to insert my code

       xl.Quit
       Set wk = Nothing
       Set wkbk = Nothing
       Set xl = Nothing
   End Sub

Thanks for any assistance!

Thanks again to dcromley for his earlier response. In the meantime, here's what I came up after a couple more searches on the Internet. It takes care of the situation where the Excel document is already open. Hopefully that will help others with similar situations, although it's not exhaustive (for example, if several Excel documents are open).

Sub DoStuffWithExcelInWordRevised()
    Dim xl As Excel.Application
    Dim wkbk As Excel.Workbook
    Dim wk As Excel.Worksheet

    On Error Resume Next
    Set xl = GetObject(, "Excel.Application")
    On Error GoTo 0

    If xl Is Nothing Then
        Set xl = CreateObject("Excel.Application")
        Set wkbk = xl.Workbooks.Open("C:\test.xlsx")
        Set wk = wkbk.Sheets(1)
    End If

    xl.Visible = True

    With xl
        ' Insert Excel code here
    End With

    Set wk = Nothing
    Set wkbk = Nothing
    Set xl = Nothing
End Sub

Try:
Add xl.Visible = True
Del xl.Quit

It appears that you are trying to do this with a Workbook that is already open. Since you want to use the open workbook / application then you need to:

Set xl = GetObject(,"Excel.Application")

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