MOCKSTACKS
EN
Questions And Answers

More Tutorials









VBA CreateObject vs GetObject

Demonstrating GetObject and CreateObject


MSDN-GetObject Function

Returns a reference to an object provided by an ActiveX component.

Use the GetObject function when there is a current instance of the object or if you want to create the object with a file already loaded. If there is no current instance, and you don't want the object started with a file loaded, use the CreateObject function.

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


Conclusion

In this page (written and validated by ) you learned about VBA CreateObject vs GetObject . What's Next? If you are interested in completing VBA tutorial, your next topic will be learning about: VBA Non Latin Characters.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.