我試圖寫採用兩個範圍和在範圍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