是否可以将文字VBA变量存储到数组中?

时间:2018-09-25 01:55:46

标签: excel vba excel-vba office365 excel-2016

我有包含大量预先计算范围变量的代码。我正在将这些变量存储到可以应用循环的数组中。我不想在循环内重新声明一些变量,因为它已经在其他地方声明了。但是,我也不想重复循环,因为代码几乎完全相同。

Dim myarray(1) as variant, I as long, cell as range
'Some code that predetermines the needed variables. Type Range
myarray(0) = Rng1
myarray(1) = Rng2
for i = 0 to 1
    for each cell in myarray(i)
        'code to loop through cells
    next cell
next i

到达for each cell in myarray(i)时得到Run-time error '424': Object required。也许我误解了数组的目的/用途。我可以使用其他方法来执行此操作,但是需要在循环中进行重新声明。由于这部分代码是大量代码的一部分,并且可能使代码混乱,因此这不是首选。

当我搜索该站点或其他站点时,我会找到短语“将变量存储到数组中”,但这是指从诸如文本文件之类的变量源中提取静态值,或对存储在变量中的值进行某种类型引用。片。我希望将类型范围的文字变量存储到其中,并能够在循环中使用它。我是不是误解了数组的声明,调用,还是它的一般用法?

2 个答案:

答案 0 :(得分:1)

有几种方法可以解决该错误。一种是在每个循环中更正集合,另一种是在校正数组。让我们知道哪个为您工作。

方法1 : 每个循环都需要一个集合对象,这与您传递的字符串不同。因此,我们宁愿使用字符串来获取范围集合,然后在单元格上循环。请改用以下代码来克服该错误。

Dim myarray(1) as String, i as long, cell as range
'Some code that predetermines the needed variables. Type Range
myarray(0) = Rng1.Address
myarray(1) = Rng2.Address
For i = 0 to 1
    For Each cell in Range(myarray(i)).Cells
        'code to loop through cells
    next cell
Next i

方法2

Dim myarray(1) as Variant, i as long, cell as range
'Some code that predetermines the needed variables. Type Range
Set myarray(0) = Rng1
Set myarray(1) = Rng2
For i = 0 to 1
    For Each cell in myarray(i).Cells
        'code to loop through cells
    next cell
Next i

答案 1 :(得分:0)

您可以将其缩短为:

For Each cell in Union(Rng1, Rng2)
    'code to loop through cells
Next cell

更新:重复代码通常使用单独的方法:

Sub method1(Range rng)
    ' code to loop through rng.Cells
End Sub

并在单独的方法中示例条件调用:

If someCondition Then method1(Rng1)