Check if an Object exists in VBScript

Armstrongest picture Armstrongest · Nov 4, 2010 · Viewed 84.6k times · Source

I'm maintaining a Classic ASP app written in VB Script by an outside company long, long ago.

I have an array of imagefile paths, like so:

dim banners, arrKeys, i
set banners=CreateObject("Scripting.Dictionary")
banners.Add "banner1.jpg", "http://www.somelink.com"
banners.Add "banner2.jpg", "http://www.somelink.com"
banners.Add "banner3.jpg", "http://www.somelink.com"

This will exist ONLY on pages that have banner ads. There is some standard code that iterates through this list in an include file (common to all pages).

If Not banners Is Nothing then 
  ' then loop through the Dictionary and make a list of image links
End if

The problem is that if banners is not instantiated on the page (it's not on all pages), I get a Can't find object error

What's the proper way to check if an object exists in VB Script?

Answer

stealthyninja picture stealthyninja · Nov 5, 2010

@Atømix: Replace

If Not banners Is Nothing then 

and use

If IsObject(banners) Then 

Your other code you can then place into an include file and use it at the top of your pages to avoid unnecessary duplication.

@Cheran S: I tested my snippets above with Option Explicit on/off and didn't encounter errors for either version, regardless of whether Dim banners was there or not. :-)