2014-02-26 84 views
1

我想将两个数组乘以每次迭代的值到电子表格中。以下是我迄今为止:在Excel VBA中乘以两个数组

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 

当我运行此我得到以下配置的运行time13错误强调:

Cells(x, x) = myArray * myArrayAdj 

有人能向我解释,我已经走了错了吗?谢谢!

+0

你的意思是内在的产品吗? – ja72

+0

为什么你的两个不同大小的数组? – sam092

回答

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。

0

整个问题从你的陈述茎就在这里:“我要乘两个阵列

我想通过你的意思是你想通过一个到多个在两个数组的各个元素,一个。

在你想要做的事这样的话:

Cells(x, x) = myArray(x) * myArrayAdj(x) 

这就是说,我不知道你的意图是否是乘法的结果存储在细胞对角线上的工作表或在其他地方

如果它是前者,那么Cells(x,x)是有意义的,但如果它是后者,则需要更加具体地说明您对两个数组的乘法期望。

+0

是的,你是正确的我想乘两个数组的单个元素并返回结果。我会测试这个。谢谢! – Chris2015

+0

我跑它,它说运行时错误9 - 下标超出范围。你知道这是为什么吗? – Chris2015

+0

@ user1813558不看你的代码很难说,但可能是因为你的数组大小不同。 – ARich