Difference between Calling a Sub and Application.Run

怎甘沉沦 提交于 2019-12-31 01:50:51

问题


In my business, we have a few teams that work on very simple macros. I'm trying to make them all readable to each other and in somewhat of a similar format, so new joiners can start working on the data.

I mention simple macros, because no one will be using Subs with arguments - most are derived from Macro Recorder anyway

Half of the teams use:

Sub button()

Call sub1()
Call sub2()
Call sub3()
Call sub4()

End Sub

And the other half use

Sub button()

Application.Run("sub1")
Application.Run("sub2")    
Application.Run("sub3")    
Application.Run("sub4")

End Sub

I understand that if your sub has no arguments, then Application.Run has a use - but being as there's barely any notation on it - is there a reason people still use Application.Run("")?

Can every use of it be beaten in speed and process by Call?


回答1:


I use Application.Run if I’m trying to run a sub that is private in another module. If I have a some kind of template where I want to hide the macros from the users I will declare it as private so they can’t run/see the macro from there macros dialog box.

In module1 I have

Private Sub priv()
  MsgBox “Private”
End Suv

In module2 the below will give you a Sub or Function not defined error.

Sub callPriv()
  Call priv()
End Sub

But in module2 this will run and display the message box

Sub callPriv()
  Application.Run “priv”
End Sub

It’s also useful to use Application.Run if you are calling a sub in your sheet or thisWorkbook modules.




回答2:


You can pass parameters through application.run as well. I use it when I am looping through macros. in your above example instead of having to write this:

Sub button()
  Call sub1()
  Call sub2()
  Call sub3()
  Call sub4()
End Sub

you could write this:

for i = 1 to 4
  application.run("sub" & i)
next i

if the subs took in a str parameter you could do this:

for i = 1 to 4
  application.run("sub" & i, strVariable)
next i


来源:https://stackoverflow.com/questions/55266228/difference-between-calling-a-sub-and-application-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!