if Excel Workbook is open then… VBA

后端 未结 3 1854
忘了有多久
忘了有多久 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:11

    First try using getobject: if it throws an error then use createobject:

      Dim xlApp As Excel.Application
    
      On Error Resume Next
      Set xlApp = GetObject(, "Excel.Application")
      On Error GoTo 0
    
      If xlApp Is Nothing Then
        Set xlApp = CreateObject("Excel.Application")
        xlApp.Visible = True
      End If
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-19 04:25

    This might be going in the wrong direction but here's something I've used in the past..

        If Workbooks.Count > 1 Then 'Or in your case = 0
           'Do Something Here'
        Else
           'Do Something Else'
        End If
    

    That way it will tell you if you have more than one workbook open. Otherwise it sounds like you ARE looking to see if something specific is open.

    Hope that helps.

    0 讨论(0)
提交回复
热议问题