访问 VBA 函数中的单个数组元素

accessing individual array elements in VBA function

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

我完全不确定我做错了什么。如果有人有解决方案,请您解释一下为什么它也有效。我感谢我能得到的所有帮助。 非常感谢!

您似乎试图将工作表范围用作从 0 开始的数组。尽管使用范围的 Cells 属性(您实际上是在隐式地尝试这样做),但这并没有什么意义:

Public Function mytest(arr1 As Range)
    Dim A As Double
    Dim B As Double

    A = arr1.Cells(1)
    B = arr1.Cells(2)

    mytest = A + B 'The actual formula is a bit more complicated than simple addition
End Function

在上面的代码中,您可以删除 Cells(),因为它将在这里用作默认值 属性,但是大多数有经验的 VBA 程序员喜欢明确说明什么 属性 他们正在使用。

这或多或少适用于一维范围,但可能无法像预期的那样适用于二维范围。 Cells 最多占用 2 个索引,一般来说,我认为当您明确说明完整索引时,代码会更清晰(例如 A = arr1.Cells(1,1)B = arr1.Cells(2,1))。

正如 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's 值,您可以在函数中创建一个内部数组,直接映射到传递的 Range.
  • 如果 Range 是真正动态的,(如 Spill 范围) 那么您只需传递锚点单元即可。

问题不在您发布的代码中,而在调用它的过程中。这里调用过程首先将值分配给工作表中的单元格(用于测试目的),然后将范围传递给将值提取到数组中的函数,然后使用该数组计算 return 值。

Private Sub TestmyTest()

    Dim Rng1 As Range

    Cells(1, "A").Value = 3.14
    Cells(2, "A").Value = 3
    Set Rng1 = Range("A1:A2")

    Debug.Print myTest(Rng1)
End Sub

Function myTest(Rng1 As Range) As Double
    ' procedures are 'Public' unless declared as 'Private'
    ' Therefore only declare "Private" or nothing
    ' Arguments are passed ByRef unless they are declared as 'ByVal'
    ' Therefore I recommend to omit "ByRef"

    Dim Arr As Variant
    Dim A As Double
    Dim B As Double

    ' this creates a 1-based 3-D array of 2 row and 1 column
    Arr = Rng1.Value

    A = Arr(1, 1)
    B = Arr(2, 1)

    myTest = A + B 'The actual formula is a bit more complicated than simple addition
End Function