VBA-UDF 以不同方式处理数组的示例
在 VBA 和 UDF(用户定义函数)中,你可以使用不同的方法处理数组,包括使用循环、数组公式、多维度数组和嵌套数组。以下是一些处理数组的示例。
Sub ProcessArray()
Dim arr(1 To 5) As Integer
Dim i As Integer
For i = 1 To 5
arr(i) = i * 2
Next i
Debug.Print "Processed Array: " & arr
End Sub
Sub FormulaArray()
Dim arr(1 To 5) As Double
Dim i As Integer
arr(1) = 2
arr(2) = 4
arr(3) = 6
arr(4) = 8
arr(5) = 10
For i = 1 To 5
arr(i) = arr(i) * (i + 1)
Next i
Debug.Print "Processed Array: " & arr
End Sub
Sub MultiDimensionalArray()
Dim arr(1 To 3, 1 To 4) As Integer
Dim i As Integer, j As Integer
arr(1, 1) = 1
arr(1, 2) = 2
arr(1, 3) = 3
arr(1, 4) = 4
arr(2, 1) = 5
arr(2, 2) = 6
arr(2, 3) = 7
arr(2, 4) = 8
arr(3, 1) = 9
arr(3, 2) = 10
arr(3, 3) = 11
arr(3, 4) = 12
For i = 1 To 3
For j = 1 To 4
arr(i, j) = arr(i, j) * (i + j)
Next j
Next i
Debug.Print "Processed Array: " & arr
End Sub
Sub NestedArray()
Dim arr(1 To 3) As Integer
Dim innerArr(1 To 3) As Integer
arr(1) = 1
arr(2) = 2
arr(3) = 3
innerArr(1) = 4
innerArr(2) = 5
innerArr(3) = 6
For i = 0 To 2
For j = 0 To 2
arr(i + j) = arr(i) * innerArr(j)
Next j
Next i
Debug.Print "Processed Array: " & arr
End Sub
Function ArrayMultiplication(arr As Variant) As Double
Dim i As Integer
Dim result As Double
For i = LBound(arr) To UBound(arr)
result = result + arr(i) * (i + 1)
Next i
ArrayMultiplication = result
End Function
Sub ArrayMultiplicationExample()
Dim arr(1 To 5) As Integer
Dim i As Integer
arr(1) = 1
arr(2) = 2
arr(3) = 3
arr(4) = 4
arr(5) = 5
For i = 1 To 5
arr(i) = arr(i) * (i + 1)
Next i
Debug.Print "Processed Array: " & arr
Dim result As Double
result = ArrayMultiplication(arr)
Debug.Print "Result: " & result
End Sub
以上示例展示了如何使用 VBA 和 UDF 按不同方式处理数组。从这些示例中,你可以根据特定需求选择适当的方法。
领取专属 10元无门槛券
手把手带您无忧上云