你有几个问题,我认为我已经纠正下面。你会注意到我的代码的一件事是我使用Variant
变量循环访问数组,而不是按编号标识元素(例如myArrayElm
而不是myArray(x)
)。这只是我个人的偏好。
Sub Test1()
Dim x As Long
Dim myArray 'Your first array
Dim myArrayElm 'A variable for the elements in your first array
Dim myArrayAdj 'Your second array
Dim myArrayAdjElm 'A variable for the elements in your second array
'Add values to your arrays
myArray = Array(24800, 26300, 27900)
myArrayAdj = Array(1.0025, 1.005, 1.0075, 1.01)
'Loop through the elements in your first array
For Each myArrayElm In myArray
'Loop through the elements in your second array
For Each myArrayAdjElm In myArrayAdj
x = x + 1
'Multiply the two array elements together
Cells(x, 1) = myArrayElm * myArrayAdjElm
Next myArrayAdjElm
Next myArrayElm
End Sub
此代码循环中两个阵列的每个元素,相乘两个元件,并且在细胞A1
开始一个列表存储的值。
现在,如果你有一个大型的数据集,下面的例子会更有效率,并且会更快完成,因为它将结果存储在另一个数组中,然后将结果一次性粘贴到表单中,而不是单独:
Option Base 1
Sub Test1()
Dim x As Long
Dim myArray 'Your first array
Dim myArrayElm 'A variable for the elements in your first array
Dim myArrayAdj 'Your second array
Dim myArrayAdjElm 'A variable for the elements in your second array
Dim Results 'An array for your results
Dim r As Range 'Range to store values
'Add values to your arrays
myArray = Array(24800, 26300, 27900)
myArrayAdj = Array(1.0025, 1.005, 1.0075, 1.01)
'Set the size of the results array
ReDim Results(1 To UBound(myArray) * UBound(myArrayAdj))
'Loop through the elements in your first array
For Each myArrayElm In myArray
'Loop through the elements in your second array
For Each myArrayAdjElm In myArrayAdj
x = x + 1
'Multiply the two array elements together
Results(x) = myArrayElm * myArrayAdjElm
Next myArrayAdjElm
Next myArrayElm
'Set the destination range
Set r = Range("A1:A" & UBound(Results))
'Paste results to sheet
r = Application.Transpose(Results)
End Sub
注意顶部的Option Base 1
。这只是意味着所有的数组现在将从元素1开始,而不是默认的元素0。
你的意思是内在的产品吗? – ja72
为什么你的两个不同大小的数组? – sam092