[英]Passing objects as parameters in Excel VBA
How do I pass an object to a private sub as a reference in Excel VBA? 如何将对象作为Excel VBA中的引用传递给私有子? Below is what I am trying to do:
以下是我要做的事情:
Sub main()
Dim r As Range
Set r = Sheets("Sheet1").Range(Cells(1, 1), Cells(27, 27))
r.Select 'this works
select_cells (r) 'this doesn't work
End Sub
Private Sub select_cells(a As Range)
a.Select 'prompts Object Required error
End Sub
select_cells (r) 'this doesn't work
You can't use parentheses to pass object parameters to a procedure. 您不能使用括号将对象参数传递给过程。 Just do this:
这样做:
select_cells r
The archaic, obsolete Call
keyword can be used, if you really want to keep the parentheses. 如果你真的想保留括号,可以使用过时的,过时的
Call
关键字。
There are severla errors in your code 您的代码中存在severla错误
Unqualified range references refer to the ActiveSheet
. 不合格的范围引用是指
ActiveSheet
。 So 所以
Set r = Sheets("Sheet1").Range(Cells(1, 1), Cells(27, 27))
will error if Sheet1
is not active. 如果
Sheet1
未激活,则会出错。
r.Select
will error if Sheet1
is not active. 如果
Sheet1
未激活,则r.Select
将出错。
select_cells (r)
with the brackets is incorrect. 带括号的
select_cells (r)
不正确。 Use 使用
select_cells r
a.Select
in the Private Sub will error if Sheet1
is not active. a.Select
。如果Sheet1
未激活,则在Private Sub中选择将出错。
Here's an modified version 这是一个修改过的版本
Sub main()
Dim r As Range
With Sheets("Sheet1")
Set r = .Range(.Cells(1, 1), .Cells(27, 27))
End With
Debug.Print r.Address ' for diagnostic purposes
select_cells r
End Sub
Private Sub select_cells(a As Range)
' Activate the worksheet first, so you can select a range on it
a.Worksheet.Select
a.Select
End Sub
Note on bracketed parameters 关于括号参数的注意事项
When a Sub
or Function
parameter is a non-object variable, bracketing the parameter overrides the ByRef
/ ByVal
definition and passes the parameter ByVal
当
Sub
或Function
参数是非对象变量时,将参数ByRef
会覆盖ByRef
/ ByVal
定义并传递参数ByVal
When a Sub
or Function
parameter is an object variable, bracketing the parameter causes an the default property to be passed to the Sub
/ Function
. 当
Sub
或Function
参数是对象变量时,将参数括起会导致将默认属性传递给Sub
/ Function
。 In the case of the OP, this is r.Value
, which causes a type missmatch. 在OP的情况下,这是
r.Value
,这导致类型不匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.