Aurelius
Aurelius

Reputation: 485

Calling a sub, with passed variables, from within a function

I have a function that is called and requires 2 passed variables

here is the first line: Function dimErr(rngStart As Long, rngEnd As Long)

Now in the middle of this function I call a sub: Call highlightLegitRows

Then the function carries on as intended.

Now, my problem is I now have optional variables associated with this sub:

Sub highlightLegitRows(Optional ByVal rngStart As Long = 0, Optional ByVal rngEnd As Long = 0)

When calling this sub, with the same values that have already been passed through, like so: Call highlightLegitRows(rngStart, rngEnd) My function appears to simply end at this line.

For example, this:

Call highlightLegitRows(rngStart, rngEnd)
MsgBox "hello"

would NOT trigger the message box. However this would:

Call highlightLegitRows
MsgBox "hello"

The only difference is the addition of these optional passed variables in the sub. Any idea where I am going wrong?

I haven't posted the whole function and sub as they are lengthy and complex, but both were working as intended before the above change.

Upvotes: 0

Views: 67

Answers (1)

Siddharth Rout
Siddharth Rout

Reputation: 149335

Your code under normal circumstances will work. For example

Sub Sample()
    Debug.Print dimErr(1, 2)
End Sub

Function dimErr(rngStart As Long, rngEnd As Long)
    Call highlightLegitRows(rngStart, rngEnd)
    MsgBox "hello"
End Function

Sub highlightLegitRows(Optional ByVal rngStart As Long = 0, _
                       Optional ByVal rngEnd As Long = 0)
    Rows(rngStart & ":" & rngEnd).Interior.ColorIndex = 3
End Sub

But will not in the below scenario.

Sub Sample()
    On Error GoTo Whoa

    Debug.Print dimErr(0, 0)        
Whoa:
End Sub

Function dimErr(rngStart As Long, rngEnd As Long)
    Call highlightLegitRows(rngStart, rngEnd)
    MsgBox "hello"
End Function

Sub highlightLegitRows(Optional ByVal rngStart As Long = 0, _
                       Optional ByVal rngEnd As Long = 0)
    Rows(rngStart & ":" & rngEnd).Interior.ColorIndex = 3
End Sub

or even this

Sub Sample()
    Debug.Print dimErr(0, 0)
End Sub

Function dimErr(rngStart As Long, rngEnd As Long)
    On Error GoTo Whoa
    Call highlightLegitRows(rngStart, rngEnd)
    MsgBox "hello"
Whoa:
End Function

Sub highlightLegitRows(Optional ByVal rngStart As Long = 0, _
                       Optional ByVal rngEnd As Long = 0)
    Rows(rngStart & ":" & rngEnd).Interior.ColorIndex = 3
End Sub

Please check your code for error handling. Is there something that is stopping (exiting the sub/function) on error?

Upvotes: 1

Related Questions