GoTo doesn't accept expression with IIF

YasserKhalil
PlatinumLounger
Posts: 4931
Joined: 31 Aug 2016, 09:02

GoTo doesn't accept expression with IIF

Post by YasserKhalil »

Hello everyone
I am trying this code

Code: Select all

Sub Test()
    Dim jumpLabel As String, n As Long
    n = 5
    jumpLabel = IIf(n = 5, "Line1", "Line2")
    GoTo jumpLabel
Line1:
    Debug.Print "Line1"
    Exit Sub
Line2:
    Debug.Print "Line2"
    Exit Sub
End Sub
but this throws an error [label not defined] at this line GoTo jumpLabel
I need to know if it is a possible logic

I can solve the problem using this version

Code: Select all

Sub Test()
    Dim n As Long
    n = 5
    If n = 5 Then GoTo Line1 Else GoTo Line2
Line1:
    Debug.Print "Line1"
    Exit Sub
Line2:
    Debug.Print "Line2"
    Exit Sub
End Sub
but I need to see if IIF will be acceptable or not.

User avatar
HansV
Administrator
Posts: 78558
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: GoTo doesn't accept expression with IIF

Post by HansV »

A label is not a text string but an instruction.

I'd avoid GoTo altogether and simply use an If ... Then ... Else ... End If block, or a Select Case ... End Case block.
Best wishes,
Hans