VBA怎么传入数组数据
时间: 2024-12-14 16:28:33 浏览: 4
在VBA(Visual Basic for Applications)中,你可以通过以下几种方式传递数组数据:
1. **ByRef参数**:如果你需要修改数组元素,可以将数组作为ByRef参数传递。例如:
```vba
Public Sub ProcessArray(ByRef arr() As Variant)
'...这里可以直接操作arr数组...
End Sub
Dim myArray(1 To 5) As Integer
Call ProcessArray myArray 'myArray会在过程内部被修改
```
2. **Pass By Value with Copy**:如果不想修改原数组,可以复制数组再传递:
```vba
Public Function ProcessCopyOfArray(arr() As Variant) As Variant
Dim tempArray() As Variant
ReDim tempArray(LBound(arr) To UBound(arr))
tempArray = arr '创建了一个副本
'...在这里处理tempArray...
ProcessCopyOfArray = tempArray
End Function
Dim myArray(1 To 5) As Integer
Dim returnedArray() As Integer
returnedArray = ProcessCopyOfArray(myArray)
```
3. **使用数组初始化子范围**:如果函数返回新数组,可以在函数内部创建:
```vba
Public Function NewArrayWithData(arr() As Variant) As Variant()
Dim newArray(sizeof(arr), 1) As Variant
'...填充newArray...
NewArrayWithData = newArray
End Function
Dim myArray(1 To 5) As Integer
Dim newArray() As Variant
newArray = NewArrayWithData(myArray)
```
阅读全文