我试图写采用两个范围和在范围1与由第二小区在范围2中的第一小区,第二小区在范围1乘以第一小区的Excel UDF(用户定义的函数)细胞在range2中,等等,然后将结果存储在一个数组中。乘法两个范围/阵列通过细胞
想象在单元格A1:A4 {1,0,1,2}中的array1和单元格B1:B4 {1,1,0,1}中的array2。我的函数VECTORMULT(A1:A4,B1:B4)将返回{1,0,0,2}。
Function VECTORMULT(array1 As Range, array2 As Range) As Variant
'takes 2 ranges and multiplies cell1 by cell1, cell2 by cell2, etc _
and stores it in a vector array
Dim Result() As Variant
Dim largerArray As Range
Dim smallerArray As Range
Dim i As Integer
'determine the smaller range to determine UBound in Result() array
If array1.Cells.Count >= array2.Cells.Count Then
Set largerArray = array1
Set smallerArray = array2
Else
Set largerArray = array2
Set smallerArray = array1
End If
ReDim Result(1 To smallerArray.Cells.Count)
'THIS IS THE PART THAT FAILS
For i = 1 To smallerArray.Cells.Count
Result(i) = largerArray.Item(i).value * smallerArray.Item(i).value
Next i
VECTORMULT = Result
End Function
我曾设想写接受了无限的ParamArray参数数量()和解析每个精氨酸作为阵列的更一般的函数,但我不能甚至解决这个看似简单的细胞迭代函数。我想VBA可以处理通过一系列在一些默认的方式像
Range(someRange).Item(i)
步进,但它不...对于它的价值,我似乎当我代替正确的行/列的indeces得到正确的价值观Item函数,如下所示;但是结果只适用于1个单元格(而不是数组)。我需要弄清楚如何通过“我”。
'substitute Item(1,1) for Item(i) and it DOES work
For i = 1 To smallerArray.Cells.Count
Result(i) = largerArray.Item(1,1).value * smallerArray.Item(1,1).value
Next i
你为什么说失败了?它错误吗?或者它只是不会产生您的预期结果?顺便说一句,它可能是一个错字,但是你的函数是'VECTORMULTrng',但是你将'Result'分配给'VECTORMULT'。 – L42 2014-10-09 23:50:42
谢谢,修复!这是尝试不同版本的功能的结果。修复此我自己的代码也引起了功能为我的代码片段最后返回正确的值,所以这是固定的。主要问题(遍历一个范围并返回一个数组)仍然存在。 – smokysunday 2014-10-10 00:05:30
要回答你的第一个问题 - 在主代码段提出的函数返回#VALUE错误。 – smokysunday 2014-10-10 00:13:19