Reputation: 21
I want to increment a number each time a sub is executed in VBScript. For example:
sub increment()
X=200
end sub
After I use the value of X
(200) for the first time when the sub is executed, the value is not valid next the time sub is executed. I need to use x=201 next time when the sub is executed. How do I set X=201, X=202, X=203 and so on every time the sub is executed?
Upvotes: 0
Views: 2490
Reputation: 5031
As @GSerg suggests, declare the X variable outside the Sub:
' Declare and Initalize X
Dim X
X = 200
Sub Increment()
X = X + 1
End Sub
The scope of X
in your question is limited to the procedure it is used in since it is not declared anywhere. You want to declare your variable at the module level. Take a look at this article from Microsoft regarding variable scope, it has a very similar example: Scope of variables in Visual Basic for Applications. Even though it is for VBA, it applies to VBScript also.
Another approach that uses the same concept is to make Increment
a Function:
Function Increment(p_iValue)
Increment = p_iValue + 1
End Function
This would be the equivalent code:
' Declare and Initalize X
Dim X
X = 200
' Do this whenever you need a new value for X
X = Increment(X)
Upvotes: 2