How to use GetObject in VBScript

VBScript GetObject documentation can be found here. Here is a VBScript sample:

Set objExcelFile = GetObject("C:\Scripts\Test.xls")
WScript.Echo objExcelFile.Name
objExcelFile.Close

This code will get you the Excel Workbook object contained in C:\Scripts\Test.xls. You can use TypeName() to confirm that:

Set objExcelFile = GetObject("C:\Scripts\Test.xls")
WScript.Echo objExcelFile.Name
WScript.Echo TypeName(objExcelFile)
objExcelFile.Close

The output will be:

test.xls
Workbook

If the specified Excel workbook doesn’t exist the script will return an error. If an instance of Excel is already running you can use this code to get a reference to it:

Set objExcel = GetObject( , "Excel.Application")

For Each objWorkbook In objExcel.Workbooks
    WScript.Echo objWorkbook.Name
Next

objExcel.Quit

Notice the comma before ‘Excel.Application’. The script gets a reference to a running Excel application, lists open workbooks names and quits Excel. If there is no Excel instance running you will receive an error. This is also why you couldn’t use GetObject() to get an instance of Scripting.FileSystemObject – there was no running instance.

You could use GetObject if there is an instance og Scripting.FileSystemObject already running in memory. Try this code:

Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFso1 = GetObject("", "Scripting.FileSystemObject")

WScript.Echo TypeName(objFso)
WScript.Echo TypeName(objFso1)

You can see that you first need to use CreateObject() to and when FileSystemObject is running it is possible to get a reference to it, but this doesn’t make much sense because you already have a reference to it (objFso). So, use CreateObject() to create an instance of FileSystemObject.

Leave a Comment