Search code examples
vbaexcelsubroutine

How to call a sub within same sub once?


I want to call a sub routine from the same sub routine based on a condition but exit out of it as soon as it's fulfilled

e.g.

Dim p as Long

Sub Main()
  Debug.Print "Start Main"
  p = 1
  call A
  Debug.Print "End Main"
End Sub

Sub A()

  Debug.Print "Start"

  if p = 1 then
     p = 2
     call A
  End if

  Debug.Print "End"

End Sub

If I run Main I will get following output this is normal since we call A twice so two start and two end

Start Main
Start
Start
End
End
End Main

But I don't want to return to the End if of sub A after it ends that sub first time meaning I want the following output if I call Main

Start Main
Start
Start
End
End Main

Notice there is only one End


Solution

  • Just add an Exit Sub where you want A() to end

    Dim p as Long
    
    Sub Main()
      Debug.Print "Start Main"
      p = 1
      call A
      Debug.Print "End Main"
    End Sub
    
    Sub A()
    
      Debug.Print "Start"
    
      if p = 1 then
         p = 2
         call A
         Exit Sub
      End if
    
      Debug.Print "End"
    
    End Sub