使用for循环计算2个数组

时间:2018-05-19 15:00:59

标签: arrays vba

我正在尝试对2个数组执行计算,然后在即时窗口中显示结果但是我收到错误说明

  

编译错误:对于每个控件变量必须是Variant或Object

两个阵列似乎都是变体 - 所以我不确定我做错了什么

Sub Main()
Application.ScreenUpdating = False
'declarations
Dim kr As Double
Dim arr As Variant
Dim varry As Variant
Dim x As Double
Dim y As Double

'declration of the 2 arrays
arr = range("ADB3:ADE3").Value
varry = range("ADB4:ADE4").Value

'nested for each loop taking each cell and tring to carry out formula
For Each x In arr
For Each y In varry

kr = ((x - y)) ^ 2 ^ 0.5 'formula taking the x from arr and the y from varry

Next varry
Next arr

'print answer
Debug.Print kr
Application.ScreenUpdating = True
End Sub

2 个答案:

答案 0 :(得分:1)

错误消息Compile error: For Each control variable must be Variant or Object中的“控制变量”是指For之后的变量,而不是您正在迭代的数组。

For Each x In arr中,控件变量为x,而不是Variant。声明它是一个变体,问题就消失了。

或者,使用类似的东西:

Dim i As Long
'...
For i = LBound(arr) To UBound(arr)
    x = arr(i)
    'etc.

答案 1 :(得分:0)

您想要的是使用.Cells而不是.Value

'declration of the 2 arrays
arr = Range("ADB3:ADE3").Cells
varry = Range("ADB4:ADE4").Cells

'nested for each loop taking each cell and tring to carry out formula
For Each x In arr
For Each y In varry

kr = ((x - y)) ^ 2 ^ 0.5 'formula taking the x from arr and the y from varry

Next varry
Next arr