Passing through variable to sub in VBA

橙三吉。 提交于 2019-12-24 22:39:42

问题


This is probably very basic, but I have tried so many things and the always give errors.

Basically what I'm trying to do is run a procedure every time a cell gets changed in Excel. So I'm using Sub Worksheet_Change(ByVal Target As Range). All works well, but in this procedure, I'm calling another sub procedure several times.

I want to reuse the 'Target' value in this procedure, but for some reason, I can't find how to do it. I tried placing 'Public rTarget As Range' and do a 'rTarget = Target' at the beginning of the procedure. But the rTarget stays empty when I call the sub procedure.

How do I make this work? I'm now adding Target as one of the variables to to subroutine, but that just looks stupid.

Thanks!


回答1:


Private Sub Worksheet_Change(ByVal Target As Range)
    MySub Target
End Sub

Sub MySub(ByVal Target As Range)
    ' Your sub code goes here and can work with the Target Range from the Worksheet_Change Event
End Sub



回答2:


Passing Target as a variable is how you should do it. You want to keep your variables in the tightest scope possible and passing them as arguments is the tightest.

If you're passing the variable to a bunch of different procedures in the same module, it may make sense to have a module-level variable. That looks like this

Private mrTarget As Range


Private Sub Worksheet_Change(ByVal Target As Range)

    Set mrTarget = Target
    MySub

End Sub

Private Sub MySub()

    Debug.Print mrTarget.Address

End Sub

Based on your questions, it's just one sub that gets called repeatedly. In that case, I would stick with passing it as an argument.



来源:https://stackoverflow.com/questions/16217537/passing-through-variable-to-sub-in-vba

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