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

Is it possible Store literal VBA Variables into an Array?

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

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。也许我误解了数组的 purpose/use 。我可以用其他方法做到这一点,但需要在循环内重新声明。由于这段代码是一组更大的代码的一部分,并且可能会搞砸,所以这不是首选。

当我搜索此网站或其他网站时,我找到了短语 "Store variables into an array,",但这些指的是从变量源(例如文本文件)或对存储在 sheet。我正在寻找将范围类型的文字变量存储到其中并能够在循环中使用它。我是否误解了数组的声明、调用或者它的一般用途?

有几种方法可以克服错误。一个是为每个循环更正集合,另一个是更正数组。让我们知道哪一个对您有用。

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

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

您可以将其缩短为:

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

Update : separate 方法常用于重复代码 :

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

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

If someCondition Then method1(Rng1)