如何在同一个sub中调用一次sub?

时间:2017-08-19 21:04:58

标签: vba excel-vba subroutine excel

我希望根据条件从同一个子例程中调用子例程,但一旦完成就退出它

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

如果我运行Main我会得到以下输出这是正常的,因为我们调用A两次所以两次开始和两次结束

Start Main
Start
Start
End
End
End Main

但是我不希望在第一次结束时返回到子A的End if,这意味着如果我调用Main,我想要以下输出

Start Main
Start
Start
End
End Main

请注意,只有一个End

2 个答案:

答案 0 :(得分:1)

只需添加Exit Sub,即希望A()结束

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

答案 1 :(得分:1)

使用else子句

var localstor = {
      userMsg : "Message",
      userInfo :{
                  ID: "SomeID",
                  username: "SomeUsername",
                  pwd : "SomePassword"
                }
    }

    //Put the localstor object into the cache
    localStorage.setItem("obj", JSON.stringify(localstor));


    //Retrieve the object
    localstor = JSON.parse(localStorage.getItem("obj"));
    //Change the username property
    localstor.userInfo.username = "AnotherUsername"; 
    //And put the editted object back to cache
    localStorage.setItem("obj", JSON.stringify(localstor));