• VB类模块中属性的参数——VBA中Range对象的Value属性和Value2属性的一点区别


    在VB中,属性是可以有参数的,而VBA中属性使用参数非常常见。比如最常用的:Worksheet.Range("A1:A10")

     VB的语法,使用参数的不一定是方法,也有可能是属性!(虽然属性的本质是方法)

    例一:参数当作“索引”使用

    定义一个类模块,模块名称Ints。为简化模型,使用了只读属性。

     1 Private arr(3) As Integer
     2 
     3 Public Property Get ArrValue(Index As Integer) As Integer
     4     ArrValue = arr(Index)
     5 End Property
     6 
     7 '初始化arr(3)的值
     8 Private Sub Class_Initialize()
     9     arr(0) = 1
    10     arr(1) = 2
    11     arr(2) = 3
    12     arr(3) = 4
    13 End Sub

    调用:

    1 Sub Test()
    2     Dim c As New Ints
    3     Debug.Print c.ArrValue(2)   'ArrValue是属性,并且带有参数( 索引 )
    4     '输出结果=3
    5 End Sub

    例2:可选参数
    定义一个类模块,模块名称MyCal。

    这个类的作用是计算两个数的和,当加数为负数时,使加数=0 (示例使用,没多少实际意义)

     1 Private m As Integer
     2 Private n As Integer
     3 
     4 Public Property Get intm() As Integer
     5     intm = m
     6 End Property
     7 
     8 Public Property Let intm(ByVal xvalue As Integer)
     9     m = xvalue
    10 End Property
    11 
    12 
    13 Public Property Get intn(Optional b As Boolean = False) As Integer
    14     intn = n
    15 End Property
    16 
    17 '加数为负数时,n赋值为0
    18 Public Property Let intn(Optional b As Boolean = False, ByVal xvalue As Integer)
    19     If b And n <= 0 Then
    20         n = 0
    21     Else
    22         n = xvalue
    23     End If
    24 End Property
    25 
    26 '计算两个数的和
    27 Public Function MySum() As Integer
    28       MySum = intm + intn
    29 End Function

    调用:

     1 Sub Test()
     2 Dim c As New MyCal
     3 
     4 c.intm = 4
     5 c.intn = -4
     6 
     7 Debug.Print c.MySum    '输出 0
     8 
     9 c.intm = 4
    10 c.intn(True) = -4
    11 
    12 Debug.Print c.MySum    '输出 4
    13 
    14 End Sub

    VBA中Range对象的Value就是有可选参数的属性

    而Range对象的另外一个属性Value2是非参数化的属性

    Value属性参数的意义:

  • 相关阅读:
    ThinkPHP5专题
    php截取中文字符串
    跨域/非跨域接口专题
    JS检查输入项是否为手机号码或者固话号码的正则表达式
    TinkPHP去重统计查询
    模型类设计模式
    经典排序方法 python
    leetcode122 买卖股票的最佳时机 python
    找到链表的倒数第k个节点 python
    链表的实现、输出和反向 python
  • 原文地址:https://www.cnblogs.com/zzstone/p/6115068.html
Copyright © 2020-2023  润新知