这里是 VBA 新手。我正在尝试将一个数组(它是静态的,但也请回答动态范围)传递给函数。然后将各个数组元素分配给唯一变量,并在自定义公式中使用这些变量。我只是浏览了一下并编写了代码,但不断收到#VALUE!错误。代码要点如下:
Public Function mytest(ByRef arr1 As Range)
Dim A As Double
Dim B As Double
A = arr1(0)
B = arr1(1)
mytest = A + B 'The actual formula is a bit more complicated than simple addition
End Function
我根本不知道我做错了什么。如果有人有解决方案,请您解释一下为什么它也有效。我感谢我能得到的所有帮助。 非常感谢!
最佳答案
正如 Coleman 指出的,范围不是数组,请考虑:
Public Function mytest(ByRef arr1 As Range)
Dim A As Double
Dim B As Double
A = arr1(1, 1)
B = arr1(2, 1)
mytest = A + B 'The actual formula is a bit more complicated than simple addition
End Function
注意:
- 我们将
Range
视为数组 - 它是二维的
- 它是基于1
- 如果您只处理
Range
值,则可以在函数中创建一个内部数组,直接映射到传递的Range
。 - 如果
范围
确实是动态的,(如溢出范围)那么您需要传递的只是 anchor 单元。
关于arrays - 在 VBA 函数中访问各个数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61610817/