我试图将两个数组相乘,将每次迭代的值放入电子表格中。以下是我到目前为止的情况:
Sub Test1()
Dim x As Long
Dim myArray
Dim myArrayAdj
myArray = Array(24800, 26300, 27900)
myArrayAdj = Array(1.0025, 1.005, 1.0075, 1.01)
For x = 1 To 1000
Cells(x, x) = myArray * myArrayAdj
Next x
End Sub
当我运行此操作时,出现Run-time13错误,突出显示以下内容:
Cells(x, x) = myArray * myArrayAdj
有人可以向我解释我哪里出错了吗?谢谢!
答案 0 :(得分:0)
整个问题源于你在此发表的声明:“我想将两个数组相乘”
我认为你的意思是你想要将两个数组中的各个元素一个接一个地复用。
在这种情况下,您想要做一些事情:
Cells(x, x) = myArray(x) * myArrayAdj(x)
那就是说,我不确定你是否打算将乘法结果存储在工作表对角线或其他地方的单元格中
如果它是前者那么Cells(x,x)
是有道理的,但如果是后者,那么你需要更加具体地说明你对两个阵列相乘的期望。
答案 1 :(得分:0)
您有一些我认为我已在下面更正的问题。您会注意到我的代码之一是我使用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。