Variable Scopes in VBScript at Windows Script Host


[This] post talks about the variables scopes in Javascript. Here, we will turn to VBScript for similar investigation upon the variable scopes. There is no closure (inner function) in VBScript, and it is therefore simpler. The VBScript, like Javascript (JScript) is not an independent programming language. It needs to be running on a hosting environment (e.g browser, windows scripting host).

At the begining (only at the first statement), you can choose to define:

1
Option Explicit
Option Explicit

This allows the VBScript interpreter to check if the variables have been defined using the keyword dim before they are referenced/used.

The first case is simple to understand, inside the function/procedure, the global variable is accessed/changed as expected.

1
2
3
4
5
6
7
8
9
10
Option Explicit
 
Dim global: global = 1
Sub Test
    global = 2
End Sub
 
MsgBox global 'print 1
Test
MsgBox global 'print 2
Option Explicit

Dim global: global = 1
Sub Test
	global = 2
End Sub

MsgBox global 'print 1
Test
MsgBox global 'print 2

If we declare the variables inside procedure/function using keyword dim similar to the var in Javascript, like this, we can prevent changing the global variable by creating a local copy, although the names are identical.

1
2
3
4
5
6
7
8
9
10
11
Option Explicit
 
Dim global: global = 1
Sub Test
    Dim global
    global = 2 'local copy actually
End Sub
 
MsgBox global 'print 1
Test
MsgBox global 'print 1
Option Explicit

Dim global: global = 1
Sub Test
	Dim global
	global = 2 'local copy actually
End Sub

MsgBox global 'print 1
Test
MsgBox global 'print 1

Without the Option Explicit, you can access a variable even if they are not defined. The following shows that with the keyword dim inside a function/procedure, anything defined stay within the local scope.

1
2
3
4
5
6
7
8
Sub Test
    Dim global
    global = 2 ' still local copy
End Sub
 
MsgBox global 'print nothing
Test
MsgBox global 'print nothing
Sub Test
	Dim global
	global = 2 ' still local copy
End Sub

MsgBox global 'print nothing
Test
MsgBox global 'print nothing

However, without dim, the procedure will create a global variable.

1
2
3
4
5
6
7
Sub Test
    global = 2  ' assign to global scope
End Sub
 
MsgBox global 'print nothing
Test
MsgBox global 'print 2
Sub Test
	global = 2  ' assign to global scope
End Sub

MsgBox global 'print nothing
Test
MsgBox global 'print 2

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
369 words
Last Post: Open A Excel File using VBScript @ Windows Script Host
Next Post: VBScript at Window Script Host, Check Folder Exists

The Permanent URL is: Variable Scopes in VBScript at Windows Script Host

Leave a Reply