在VB中,属性是可以有参数的,而VBA中属性使用参数非常常见。比如最常用的:Worksheet.Range("A1:A10")
VB的语法,使用参数的不一定是方法,也有可能是属性!(虽然属性的本质是方法)
例一:参数当作“索引”使用
定义一个类模块,模块名称Ints。为简化模型,使用了只读属性。
Private arr() As Integer Public Property Get ArrValue(Index As Integer) As Integer
ArrValue = arr(Index)
End Property '初始化arr(3)的值
Private Sub Class_Initialize()
arr() =
arr() =
arr() =
arr() =
End Sub
调用:
Sub Test()
Dim c As New Ints
Debug.Print c.ArrValue() 'ArrValue是属性,并且带有参数( 索引 )
'输出结果=3
End Sub
例2:可选参数
定义一个类模块,模块名称MyCal。
这个类的作用是计算两个数的和,当加数为负数时,使加数=0 (示例使用,没多少实际意义)
Private m As Integer
Private n As Integer Public Property Get intm() As Integer
intm = m
End Property Public Property Let intm(ByVal xvalue As Integer)
m = xvalue
End Property Public Property Get intn(Optional b As Boolean = False) As Integer
intn = n
End Property '加数为负数时,n赋值为0
Public Property Let intn(Optional b As Boolean = False, ByVal xvalue As Integer)
If b And n <= Then
n =
Else
n = xvalue
End If
End Property '计算两个数的和
Public Function MySum() As Integer
MySum = intm + intn
End Function
调用:
Sub Test()
Dim c As New MyCal c.intm =
c.intn = - Debug.Print c.MySum '输出 0 c.intm =
c.intn(True) = - Debug.Print c.MySum '输出 4 End Sub
VBA中Range对象的Value就是有可选参数的属性
而Range对象的另外一个属性Value2是非参数化的属性
Value属性参数的意义: