I am new to VBScript, and I learned that VBScript does not have return and that to return a value, you assign the value to the name of the procedure.
When I was doing research on how to return a value, I found two different programs that both return a value, and I am not sure what the difference is.
Function Test1()
Dim value
'Do something'
If value < 10 Then
Test1 = value * 2
Else
Test1 = value
End If
End Function
Function Test2()
Dim value
'Do something'
If value < 10 Then
Test2 = value * 2
Exit Function
Else
Test2 = value
Exit Function
End If
End Function
It seems like Exit Function exits the procedure immediately when this program comes to this line, but what is the necessity of this line of code?
I have been learning other major programming languages such as C#, Java, etc, and in those programming languages, once the program comes to the line return or return something, the program exits that function/method even if there is mode code after that.
Does this mean, in VBScript, assigning a value to the name of its own procedure serves as return but it still keeps going without exiting until the end of the procedure unless you use Exit Function?
VBScript needs the Exit Function command if you want to instruct the function to return IMMEDIATELY instead of continuing the function. To assign the return value in VBScript, you use FUNCTIONNAME=VALUE_TO_RETURN. But in VBScript, that type of statement DOES NOT EXIT THE FUNCTION (although in C-like languages the assignment to the return value (return X;) exits the function immediately.)
For example, say you're trying to generate a filename that doesn't exist yet.
Function GenName( ROOT, file )
targetPath = ROOT & "\" & file.Name
If Not ofso.FileExists( targetPath ) Then
' ASSIGN RETURN VALUE THEN..
GenName = targetPath
Exit Function ' __GET OUT OF THE FUNCTION__
' If you neglect EXIT FUNCTION here, then
' THIS FUNCTION WILL CONTINUE RUNNING TO THE END
' OF IT, even though YOU'VE ALREADY ASSIGNED THE FUNCTION
' A RETURN VALUE
End If
For num = 1 To 10000
' append numbers until you find one that doesn't exist or quit
targetPath = ROOT & "\" & ofso.GetBaseName( file ) & "-" & num & "." & ofso.GetExtensionName( file )
If Not ofso.FileExists( targetPath ) Then
GenName = targetPath ' WANTS to be "return targetPath"
' but you can't do that in VBSCRIPT. So ASSIGN VALUE to
' function name.. AND THEN..
Exit Function '' MUST EXIT FUNCTION otherwise function
' will just continue to run (for loop will keep executing)
' else can break loop with EXIT FOR
End If
Next
End Function
Specifying the function's return value and returning to the caller (via reaching the end of the function's body or an explicit statement) are clearly different things. Being able to express both distinctly is a pro:
>> Function preinc(ByRef i) : i = i + 1 : preinc = i : End Function
>> Function postinc(ByRef i) : postinc = i : i = i + 1 : End Function
>> i = 0
>> WScript.Echo i
>> WScript.Echo preinc(i), i
>> WScript.Echo postinc(i), i
>>
0
1 1
1 2
Languages that combine setting the value and leaving the function (return(x), returning the value of the 'last' expression) don't let you do work or cleanup (cf. here) after determining the return value.
I must be overlooking something painfully obvious. The following code fails on the Next line with the error message "Expected end of statement":
Option Explicit
GetB
Sub GetB()
Dim i
For i = 1 to 2
Msgbox i
Next i
End Sub
Found it. The repetition of the loop variable ("i") in the Next statement, which is legal and optional in every other BASIC-like (B*SIC?) language, is illegal in VBS.
The code should read:
Option Explicit
GetB
Sub GetB()
Dim i
For i = 1 to 2
Msgbox i
Next
End Sub
What is the best way in VB6 to pass an error back to the calling function?
1 On Error Resume Next
2 ' do something
3 If Err.Number <> 3026 Or Err <> 0 Then ?????????
How would you send the error in Line 3 back to the calling function? Is the following the only way to achieve this?
errNum = Err.Number
On Error Goto 0
Err.Raise errNum
Use On Error GoTo and re-raise the error in the handler with Err.Raise.
Private Function DoSomething(ByVal Arg as String)
On Error GoTo Handler
Dim ThisVar as String
Dim ThatVar as Long
' Code here to implement DoSomething...
Exit Function
Handler:
Err.Raise Err.Number, , "MiscFunctions.DoSomething: " & Err.Description
End Function
You'll then be able to get the error number and description in the caller via Err.Number and Err.Description.
If the caller is also using On Error GoTo, you'll see them in the handler there.
If the caller is using On Error Resume Next, then you can still use those same variables inline.
I prefer the first option, using On Error Goto in all functions and subs, because it seems like the natural way to use VB6's built-in error raising features. You can also update the description in the called function's handler, like the example above, and get a pseudo call stack you can eventually log or display to yourself during debugging.
More VB6 error handling thoughts here:
Is it possible to retrieve the call stack programmatically in VB6?
How to clean up error handling in a function?
Why not add ByRef errorCode as Long to the called function's args and set it equal to Err.Number after ' do something
Or you could have a public field called ErrorCode as Long that you could set after ' do something
I have worked with a lot of industrial control APIs and both of these methods have been used.
You can easily send the error to the upper (calling) sub/function as long as the function that raises the error does not have (ON ERROR RESUME ---), that way, error handling is left in the upper level only. Otherwise you will have to handle the error inside the called function
Private Sub Command1_Click()
Dim test As Integer
On Error Resume Next
test = myFunction 'Calling a function that is known to have an error
If Err <> 0 Then
MsgBox "MyFunction failed because:" & Err.Description 'Error is passed
End If
End Sub
'--------------------------
Function myFunction() As Integer
Dim i As Integer
i = 1
i = 4 / 0 'This will raise an Error, and control returns to the calling sub
i = 2 'This will never get executed
myFunction = i
End Function
If you simply want to pass the error back to the original caller without handling it, then you want to remove any ON ERROR in the child function:
Public Sub ParentSub()
On Error GoTo ErrorHandler
' do something
Call ChildSub()
' do something
Exit Sub
ErrorHandler:
' handle the error here
End Sub
Public Sub ChildSub()
' do something
' if there is an error here, the error will be handled in ErrorHandler of ParentSub
End Sub
or if you want to handle it in both subs:
Public Sub ParentSub()
On Error GoTo ErrorHandler
' do something
Call ChildSub()
' do something
Exit Sub
ErrorHandler:
' handle the error here
End Sub
Public Sub ChildSub()
On Error GoTo ErrorHandler
' do something
Exit Sub
ErrorHandler:
' handle the error here and pass it back to the ParentSub to handle it as well
Err.Raise Err.Number
End Sub
Bah, vbscript.
I'm trying to figure out how to get this statement to work:
if (not rsObject("columnNameThatDoesntExist") is nothing) then
' do some stuff
end if
' else do nothin
Where rsObject is a RecordSet and columnNameThatDoesntExist is ... well you know. I'm looking for something like rsObject.Columns.Contains(string). But of course can't find it.
Edit: Looks like looping rsObject.Fields is an option, is that the only way to do this?
I am sure you have your reasons, but if you don't know what fields you are calling back from your database, you could always use On Error Resume Next and On Error Goto 0 to ignore the tossed error. Seems like a bad way to me, but it would work
blnItWasntThere = True
On Error Resume Next
If (rsObject("columnNameThatDoesntExist") <> "") Then
blnItWasntThere = False
...
...
...
End If
On Error Goto 0
If blnItWasntThere Then
'handle this error'
End If
But with that said, I think you would be more worried about the mystery recordset you are getting back.
Or make your own function
Function ColumnExists(objRS, Column)
Dim blnOutput, x
blnOutput = True
On Error Resume Next
x = objRS(Column)
If err.Number <> 0 Then blnOutput = False
On Error Goto 0
ColumnExists = blnOutput
End Function
Either looooop and check if it's there, or just try to grab it:
Dim oRs:Set oRs = Nothing
On Error Resume Next
Set oRs = rsObject("columnNameThatDoesntExist")
On Error Goto 0
If Not rsObject("columnNameThatDoesntExist" Is Nothing Then
' ...
End If
I've inherited a large VB6 app at my current workplace. I'm kinda learning VB6 on the job and there are a number of problems I'm having. The major issue at the moment is I can't figure out how to check if a key exists in a Collection object. Can anyone help?
My standard function is very simple. This will work regardless of the element type, since it doesn't bother doing any assignment, it merely executes the collection property get.
Public Function Exists(ByVal oCol As Collection, ByVal vKey As Variant) As Boolean
On Error Resume Next
oCol.Item vKey
Exists = (Err.Number = 0)
Err.Clear
End Function
#Mark Biek Your keyExists closely matches my standard Exists() function. To make the class more useful for COM-exposed collections and checking for numeric indexes, I'd recommend changing sKey and myCollection to not be typed. If the function is going to be used with a collection of objects, 'set' is required (on the line where val is set).
EDIT: It was bugging me that I've never noticed different requirements for an object-based and value-based Exists() function. I very rarely use collections for non-objects, but this seemed such a perfect bottleneck for a bug that would be so hard to track down when I needed to check for existence. Because error handling will fail if an error handler is already active, two functions are required to get a new error scope. Only the Exists() function need ever be called:
Public Function Exists(col, index) As Boolean
On Error GoTo ExistsTryNonObject
Dim o As Object
Set o = col(index)
Exists = True
Exit Function
ExistsTryNonObject:
Exists = ExistsNonObject(col, index)
End Function
Private Function ExistsNonObject(col, index) As Boolean
On Error GoTo ExistsNonObjectErrorHandler
Dim v As Variant
v = col(index)
ExistsNonObject = True
Exit Function
ExistsNonObjectErrorHandler:
ExistsNonObject = False
End Function
And to verify the functionality:
Public Sub TestExists()
Dim c As New Collection
Dim b As New Class1
c.Add "a string", "a"
c.Add b, "b"
Debug.Print "a", Exists(c, "a") ' True '
Debug.Print "b", Exists(c, "b") ' True '
Debug.Print "c", Exists(c, "c") ' False '
Debug.Print 1, Exists(c, 1) ' True '
Debug.Print 2, Exists(c, 2) ' True '
Debug.Print 3, Exists(c, 3) ' False '
End Sub
I've always done it with a function like this:
public function keyExists(myCollection as collection, sKey as string) as Boolean
on error goto handleerror:
dim val as variant
val = myCollection(sKey)
keyExists = true
exit sub
handleerror:
keyExists = false
end function
As pointed out by Thomas, you need to Set an object instead of Let. Here's a general function from my library that works for value and object types:
Public Function Exists(ByVal key As Variant, ByRef col As Collection) As Boolean
'Returns True if item with key exists in collection
On Error Resume Next
Const ERR_OBJECT_TYPE As Long = 438
Dim item As Variant
'Try reach item by key
item = col.item(key)
'If no error occurred, key exists
If Err.Number = 0 Then
Exists = True
'In cases where error 438 is thrown, it is likely that
'the item does exist, but is an object that cannot be Let
ElseIf Err.Number = ERR_OBJECT_TYPE Then
'Try reach object by key
Set item = col.item(key)
'If an object was found, the key exists
If Not item Is Nothing Then
Exists = True
End If
End If
Err.Clear
End Function
As also advised by Thomas, you can change the Collection type to Object to generalize this. The .Item(key) syntax is shared by most collection classes, so that might actually be useful.
EDIT Seems like I was beaten to the punch somewhat by Thomas himself. However for easier reuse I personally prefer a single function with no private dependencies.
Using the error handler to catch cases when the key does not exists in the Collection can make debugging with "break on all errors" option quite annoying. To avoid unwanted errors I quite often create a class which has the stored objects in a Collection and all keys in a Dictionary. Dictionary has exists(key) -function so I can call that before trying to get an object from the collection. You can only store strings in a Dictionary, so a Collection is still needed if you need to store objects.
The statement "error handling will fail if an error handler is already active" is only partly right.
You can have multiple error handlers within your routine.
So, one could accommodate the same functionality in only one function.
Just rewrite your code like this:
Public Function Exists(col, index) As Boolean
Dim v As Variant
TryObject:
On Error GoTo ExistsTryObject
Set v = col(index)
Exists = True
Exit Function
TryNonObject:
On Error GoTo ExistsTryNonObject
v = col(index)
Exists = True
Exit Function
ExistsTryObject:
' This will reset your Err Handler
Resume TryNonObject
ExistsTryNonObject:
Exists = False
End Function
However, if you were to only incorporate the code in the TryNonObject section of the routine, this would yield the same information.
It will succeed for both Objects, and non-objects.
It will speed up your code for non-objects, however, since you would only have to perform one single statement to assert that the item exists within the collection.
Better solution would be to write a TryGet function. A lot of the time you are going to be checking exists, and then getting the item. Save time by doing it at the same time.
public Function TryGet(key as string, col as collection) as Variant
on error goto errhandler
Set TryGet= col(key)
exit function
errhandler:
Set TryGet = nothing
end function
see
http://www.visualbasic.happycodings.com/Other/code10.html
the implementation here has the advantage of also optionally returning the found element, and works with object/native types (according to the comments).
reproduced here since the link is no longer available:
Determine if an item exists in a collection
The following code shows you how to determine if an item exists within a collection.
Option Explicit
'Purpose : Determines if an item already exists in a collection
'Inputs : oCollection The collection to test for the existance of the item
' vIndex The index of the item.
' [vItem] See Outputs
'Outputs : Returns True if the item already exists in the collection.
' [vItem] The value of the item, if it exists, else returns "empty".
'Notes :
'Example :
Function CollectionItemExists(vIndex As Variant, oCollection As Collection, Optional vItem As Variant) As Boolean
On Error GoTo ErrNotExist
'Clear output result
If IsObject(vItem) Then
Set vItem = Nothing
Else
vItem = Empty
End If
If VarType(vIndex) = vbString Then
'Test if item exists
If VarType(oCollection.Item(CStr(vIndex))) = vbObject Then
'Return an object
Set vItem = oCollection.Item(CStr(vIndex))
Else
'Return an standard variable
vItem = oCollection.Item(CStr(vIndex))
End If
Else
'Test if item exists
If VarType(oCollection.Item(Int(vIndex))) = vbObject Then
'Return an object
Set vItem = oCollection.Item(Int(vIndex))
Else
'Return an standard variable
vItem = oCollection.Item(Int(vIndex))
End If
End If
'Return success
CollectionItemExists = True
Exit Function
ErrNotExist:
CollectionItemExists = False
On Error GoTo 0
End Function
'Demonstration routine
Sub Test()
Dim oColl As New Collection, oValue As Variant
oColl.Add "red1", "KEYA"
oColl.Add "red2", "KEYB"
'Return the two items in the collection
Debug.Print CollectionItemExists("KEYA", oColl, oValue)
Debug.Print "Returned: " & oValue
Debug.Print "-----------"
Debug.Print CollectionItemExists(2, oColl, oValue)
Debug.Print "Returned: " & oValue
'Should fail
Debug.Print CollectionItemExists("KEYC", oColl, oValue)
Debug.Print "Returned: " & oValue
Set oColl = Nothing
End Sub
See more at: https://web.archive.org/web/20140723190623/http://visualbasic.happycodings.com/other/code10.html#sthash.MlGE42VM.dpuf
While looking for a function like this i designed it as following.
This should work with objects and non-objects without assigning new variables.
Public Function Exists(ByRef Col As Collection, ByVal Key) As Boolean
On Error GoTo KeyError
If Not Col(Key) Is Nothing Then
Exists = True
Else
Exists = False
End If
Exit Function
KeyError:
Err.Clear
Exists = False
End Function