在多个命名范围上执行相同的操作

问题描述 投票:0回答:4

我在工作表中有一堆命名范围,每天必须清除。目前我在VBA中设置如下:

Range("CustomList1").ClearContents
Range("CustomList2").ClearContents
Range("CustomList3").ClearContents
Range("CustomList4").ClearContents
Range("CustomList5").ClearContents
(+15 more)

这并不是什么大不了的事,但我觉得必须有一个更好的方法来实现它。在做了一些搜索之后,我没有看到任何关于循环多个命名范围的事情。有关于此的任何想法/想法?

excel vba
4个回答
2
投票
Dim i As Long

For i = 1 to 20
    Range("CustomList" & i).ClearContents
Next

......那样的事情。

如果您想要清除命名范围的某种命名约定,那么您可以执行类似这样的操作,这意味着您无需更新代码...

Dim objName As Name

For Each objName In ThisWorkbook.Names
    If InStr(1, objName.Name, "NamedRange", vbTextCompare) = 1 Then
        With objName.RefersToRange
            .Worksheet.Range(.Address).ClearContents
        End With
    End If
Next

1
投票

如果名称一致,Skin的解决方案将起作用,但如果不一致,您可以始终创建一个包含所有范围名称的数组。

就像是

RngArray = Array("CustomList1","CustomList2","CustomList3, etc.") For i = 0 to 19 Range(RngArray(i)).ClearContents Next


1
投票

联合可能比循环更多地键入,但它在单个语句中完成操作。

Union(Range("CustomList1"), Range("CustomList2"), Range("CustomList3"), _
      Range("CustomList4"), Range("CustomList5"), Range("CustomList6"), _
      Range("CustomList7"), Range("CustomList8"), Range("CustomList9"), _
      Range("CustomList10"), Range("CustomList11"), Range("CustomList12"), _
      Range("CustomList13"), Range("CustomList14"), Range("CustomList15"), _
      Range("CustomList16"), Range("CustomList17"), Range("CustomList18"), _
      Range("CustomList19"), Range("CustomList20")).ClearContents

此方法可能更适合具有抽象或不相似命名约定的命名范围。


1
投票

我会稍微改变一下。

我会将名称存储在公式==>名称管理器中的一个名称下,如下所示。

enter image description here

然后我将只使用下面的每个地方。每次要清除范围时都不需要多行代码。

Range("MyCustomList").ClearContents
© www.soinside.com 2019 - 2024. All rights reserved.