演示 GetObject 和 CreateObject
返回對 ActiveX 元件提供的物件的引用。
當存在物件的當前例項時,或者如果要建立已載入檔案的物件,請使用 GetObject 函式。如果沒有當前例項,並且你不希望以載入檔案的方式啟動物件,請使用 CreateObject 函式。
Sub CreateVSGet()
Dim ThisXLApp As Excel.Application 'An example of early binding
Dim AnotherXLApp As Object 'An example of late binding
Dim ThisNewWB As Workbook
Dim AnotherNewWB As Workbook
Dim wb As Workbook
'Get this instance of Excel
Set ThisXLApp = GetObject(ThisWorkbook.Name).Application
'Create another instance of Excel
Set AnotherXLApp = CreateObject("Excel.Application")
'Make the 2nd instance visible
AnotherXLApp.Visible = True
'Add a workbook to the 2nd instance
Set AnotherNewWB = AnotherXLApp.Workbooks.Add
'Add a sheet to the 2nd instance
AnotherNewWB.Sheets.Add
'You should now have 2 instances of Excel open
'The 1st instance has 1 workbook: Book1
'The 2nd instance has 1 workbook: Book2
'Lets add another workbook to our 1st instance
Set ThisNewWB = ThisXLApp.Workbooks.Add
'Now loop through the workbooks and show their names
For Each wb In ThisXLApp.Workbooks
Debug.Print wb.Name
Next
'Now the 1st instance has 2 workbooks: Book1 and Book3
'If you close the first instance of Excel,
'Book1 and Book3 will close, but book2 will still be open
End Sub