I've been battling with vba for a bit and surprisingly it's not getting much better. I have written the following code so I can have a special comparison operator for an object.
Public Function myEquals(v As CCtypestore) As Boolean
If v Is Nothing Then
myEquals = False
Return
End If
If Me.Acronym = v.Acronym Then
myEquals = True
Return
End If
myEquals = False
Return
End Function
The object v I'm passing in is Nothing at the moment so I would have sort of expected the result to be a trivial False. Surprisingly instead I'm getting an error Return without gosub. Any clue why that might be?
When called within VBA the function will return a range object, but when called from a worksheet it will return just the value, so set test = Range("A1") is exactly equivalent to test = Range("A1"). Value , where "test" is defined as a Variant, rather than a Range.
AutoCAD to Excel - VBA Programming Hands-On!Sub procedures DO NOT Return a value while functions may or may not return a value. Sub procedures CAN be called without a call keyword. Sub procedures are always enclosed within Sub and End Sub statements.
VBA functions (and other programming languages as well) can only return one value.
Delete the Return
statements!
In VBA, you set the return value with the line myEquals = ...
.
All in all, you can reduce your function to the following code:
Public Function myEquals(v As CCtypestore) As Boolean
If Not v Is Nothing Then
myEquals = (Me.Acronym = v.Acronym)
End If
End Function
Alternatively, use this:
Public Function myEquals(v As CCtypestore) As Boolean
On Error Goto ErrorHandler
myEquals = (Me.Acronym = v.Acronym)
Exit Function
ErrorHandler:
myEquals = False
End Function
Return
is an old relic if you want to work with direct jumps in the code, i.e. build spaghetti code! See this example from the help file:
Sub GosubDemo()
Dim Num
' Solicit a number from the user.
Num = InputBox("Enter a positive number to be divided by 2.")
' Only use routine if user enters a positive number.
If Num > 0 Then GoSub MyRoutine
Debug.Print Num
Exit Sub ' Use Exit to prevent an error.
MyRoutine:
Num = Num/2 ' Perform the division.
Return ' Return control to statement.
End Sub ' following the GoSub statement.
Use Exit Function
instead of Return
.
You can also avoid those Exit Function
by using a construction like
If .... Then
'some code
ElseIf...Then
'some other code
ElseIf...Then
'etc
Else
'final
End if
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With