Reputation: 330
I am having an issue with VBS variable value assignment:
Dim varName
varName = function(x, y)
varName = function(x, y)
function is a recursive function, which calls itself:
Function function(x, y)
If IsObject(dicColumnIndices) Then
function = CInt(dicColumnIndices.Item(y))
Else
Set oCDSGrid = %MyAppObject%
Set dicColumnIndices = CreateObject("Scripting.Dictionary")
intColumnCount = oCDSGrid.ActiveSheet.Columns.Count
For i = 0 To intColumnCount - 1
dicColumnIndices.Add oCDSGrid.ActiveSheet.Columns.Item(i).Label, i
Next
function x, y
End If
End Function
As far as I can see, the variable value assignment only happens on the second try. I figured it has something to do with my function recursively calling itself (the issue is gone in case I remove the recursive call), but I shall very much like to learn what are the roots of this behaviour.
I looked up both StackOverflow and the Internet with no luck.
Edit: In order to solve this issue, I had to remove the recursive call:
Function function(x, y)
If IsObject(dicColumnIndices) Then
function = CInt(dicColumnIndices.Item(y))
Else
Set oCDSGrid = %MyAppObject%
Set dicColumnIndices = CreateObject("Scripting.Dictionary")
intColumnCount = oCDSGrid.ActiveSheet.Columns.Count
For i = 0 To intColumnCount - 1
dicColumnIndices.Add oCDSGrid.ActiveSheet.Columns.Item(i).Label, i
Next
function = CInt(dicColumnIndices.Item(y))
End If
End Function
Edit 2: Finally, with help from MSDN I got the wrong part - it is the second call
function x, y
which returns the value into nothing, must be changed to:
function = function x, y
Thanks everyone!
Upvotes: 0
Views: 1230
Reputation: 38745
A function shouldn't be called function, and varname is a lousy name for a variable. More to the point: In VBScript a function isn't a function (does not return something) if you don't 'assign to the function name':
Dim s : s = "abcdefg"
Dim l : l = recLen(s)
WScript.Echo "recursive length of", qq(s), "=>", l, CStr(l = Len(s))
Function recLen(s)
If "" = s Then
recLen = 0
Else
recLen = 1 + recLen(Mid(s, 2))
End If
End Function
(The length of an empty string is 0; for longer strings it's 1 + the length of the string's 'tail')
Update (thanks to AutomatedChaos):
Function qq( vStringable )
qq = """" & vStringable & """"
End Function
Update II (to answer Eugene's question in comment):
To make a function to return something, you'll have to assign the value to return to a variable having the same name as the function. Your original code didn't (even if the name "function" was replaced by the 'real' name).
Upvotes: 1