if Excel Workbook is open then… VBA

后端 未结 3 1887
忘了有多久
忘了有多久 2021-01-19 03:45

How could I write code to say.

    Dim xlApp As Excel.Application
    Dim xlWorkbook As Excel.Workbook
    Dim xlWorksheet As Excel.Worksheet
3条回答
  •  长发绾君心
    2021-01-19 04:15

    I used to run code very similar to Tim's until Kevin Jones pointed out in an Experts-Exchange post that I will repeat here (as the EE post is behind the paywall)

    "Be aware that when launching Excel through automation using the CreateObject function, Excel does not load any Add-Ins or other workbooks normally loaded automatically. This is not a good way to start an Excel session that will be used by the user. To start an Excel application instance without using automation from any application other than Excel, the Excel application must be launched using non-automation means. The code below illustrates the steps to do this. The code first tries to obtain an automation handle to an existing application instance. If an existing instance is not found then a new instance is started using the Shell command."

     Dim ExcelApplication As Object
       Dim TimeoutTime As Long
    
       On Error Resume Next
       Set ExcelApplication = GetObject(, "Excel.Application")
       On Error GoTo 0
       If ExcelApplication Is Nothing Then
           Shell "Excel.exe"
           TimeoutTime = Timer + 5
           On Error Resume Next
           Do
               DoEvents
               Err.Reset
               Set ExcelApplication = GetObject(, "Excel.Application")
           Loop Until Not ExcelApplication Is Nothing Or Timer > TimeoutTime
           On Error GoTo 0
       End If
       If ExcelApplication Is Nothing Then
           MsgBox "Unable to launch Excel."
       Else
           ' Do something with the Excel instance...
       End If
    

提交回复
热议问题