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屬性參數的意義:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM