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

时光总嘲笑我的痴心妄想 提交于 2019-12-25 07:18:06

问题


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!


回答1:


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




回答2:


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")



回答3:


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


来源:https://stackoverflow.com/questions/24169850/how-to-switch-to-open-excel-spreadsheet-and-work-on-it-from-word-with-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!