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

问题描述 投票:0回答:2

我是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

我不知道我到底做错了什么。如果有人有解决办法,请你解释一下为什么它也能工作。I appreciate any and all help I can get.Many thanks !

arrays excel vba function excel-2010
2个回答
2
投票

正如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

enter image description here

注意:

  • 我们把 Range 类似于数组
  • 是二维的
  • 1 基于
  • 如果你只是在处理 Range's 值,你可以在函数中创建一个内部数组,直接映射到传递的 Range.
  • 如果 Range 是真正的动态。(像溢出范围) 那么你需要传递的只是锚单元格。

2
投票

你似乎是想把工作表范围作为一个基于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)).


2
投票

问题不在你发布的代码中,而是在调用它的过程中。这里,调用过程首先为工作表中的单元格赋值(为了测试目的),然后将范围传递给函数,函数将值提取到一个数组中,然后使用该数组计算一个返回值。

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
© www.soinside.com 2019 - 2024. All rights reserved.