VBA将所有范围变量添加到数组

时间:2015-12-12 22:20:51

标签: arrays vba variables range

我有一个VBA程序,我在一个选项卡上设置了150多个范围变量。我试图找出一种方法来清除与这些变量相关的所有范围的内容,到目前为止,我能想到的唯一方法是逐个使用每个变量的.ClearContents方法。例如:

Sub rangeVariableQuestion()

Dim personnel As Range
Dim dateAndTime As Range
Dim companyName As Range
Dim reportDate As Range

''''''''''''''''''' + 150+ more variables

Set personnel = Range("Personnel")
Set dateAndTime = Range("Date")
Set companyName = Range("Company")
Set reportDate = Range("reportdate")

'''''''''''''''

personnel.ClearContents
dateAndTime.ClearContents
companyName.ClearContents
reportDate.ClearContents

'''''''''''''''''''    

End Sub

有没有办法可以将程序中的所有变量都放到数组中?这样我就可以遍历每个变量来清除内容。

1 个答案:

答案 0 :(得分:0)

我可能会选择Range objects数组,我可以循环使用或在150+范围内使用Union method

Sub rangeVariableQuestion()

    Dim personnel As Range
    Dim dateAndTime As Range
    Dim companyName As Range
    Dim reportDate As Range
    Dim nukeThese As Range

    ''''''''''''''''''' + 150+ more variables

    Set personnel = Range("Personnel")
    Set dateAndTime = Range("Date")
    Set companyName = Range("Company")
    Set nukeThese = Union(personnel, dateAndTime, companyName)   '<~~ start off by setting to the union of three
    Set reportDate = Range("reportdate")
    Set nukeThese = Union(nukeThese, reportDate)                 '<~~ continue by setting union to self and other(s)

    '''''''''''''''

    'clear the unioned range    
    nukeThese.ClearContents
    'or just clear the union directly
    Union(personnel, dateAndTime, companyName, reportDate).ClearContents

    '''''''''''''''''''

End Sub

在一个命令中可以使用Union method直接解决的不连续范围的数量有限制。您应该能够在一个联盟中解决最多30个问题。之后,联盟原来还有29个。

相关问题