vba中如何使用ubound

在VBA(Visual Basic for Applications)中,`UBound` 函數(shù)用于獲取數(shù)組中指定維度的最大索引。這對(duì)于處理數(shù)組時(shí)確定其邊界非常有用。以...
在VBA(Visual Basic for Applications)中,`UBound` 函數(shù)用于獲取數(shù)組中指定維度的最大索引。這對(duì)于處理數(shù)組時(shí)確定其邊界非常有用。
以下是如何使用 `UBound` 函數(shù)的示例:
```vba
Sub 使用UBound示例()
Dim myArray() As Integer
ReDim myArray(1 To 5) ' 創(chuàng)建一個(gè)具有5個(gè)元素的數(shù)組
' 填充數(shù)組
For i = LBound(myArray) To UBound(myArray)
myArray(i) = i
Next i
' 打印數(shù)組元素
For i = LBound(myArray) To UBound(myArray)
Debug.Print "myArray(" & i & ") = " & myArray(i)
Next i
End Sub
```
在這個(gè)例子中:
`ReDim myArray(1 To 5)` 創(chuàng)建了一個(gè)具有5個(gè)元素的數(shù)組,索引從1到5。
`LBound(myArray)` 返回?cái)?shù)組的第一個(gè)索引,即1。
`UBound(myArray)` 返回?cái)?shù)組的最后一個(gè)索引,即5。
`UBound` 函數(shù)可以用于任何維度的數(shù)組,并且可以與 `LBound` 函數(shù)一起使用來確保不會(huì)超出數(shù)組的邊界。
如果你想獲取特定維度的最大索引,你可以將維度作為 `UBound` 函數(shù)的第二個(gè)參數(shù)傳遞:
```vba
Dim myArray(1 To 5, 1 To 3) As Integer ' 創(chuàng)建一個(gè)二維數(shù)組
' 獲取第一維的最大索引
Dim firstDimensionUBound As Integer
firstDimensionUBound = UBound(myArray, 1)
' 獲取第二維的最大索引
Dim secondDimensionUBound As Integer
secondDimensionUBound = UBound(myArray, 2)
```
在上面的代碼中,`myArray` 是一個(gè)二維數(shù)組,`UBound(myArray, 1)` 返回第一維的最大索引(5),而 `UBound(myArray, 2)` 返回第二維的最大索引(3)。
本文鏈接:http://xinin56.com/bian/350104.html