我在同一张纸上有多个命名范围,我想通过单击按钮取消隐藏所有使用VBA的范围。命名范围的示例:April_name1。同一张纸上的第二个是April_name2。因此,所有范围都以前面的相同代码开头:April_。
我如何遍历以April_开头的所有范围并取消隐藏?
其他人已经在这里(VBA Excel select named range starting with character)提出了类似的问题,我认为他们的代码答案(针对我上面的情况进行了修改)如下:
Sub April_button_Click()
Dim NamedRange As Name
For Each NamedRange In ActiveWorkbook.Names
If UCase(Left(NamedRange.Name, 6)) = "April_" Then
Range(NamedRange.RefersTo).EntireRow.Hidden = False
End If
Next NamedRange
End Sub
我不想创建重复的问题,但是当我单击按钮时,上面的代码根本无法运行,甚至没有错误消息。有什么线索吗?谢谢
答案 0 :(得分:0)
您使用UCase的方式错误 UCASE Left永远不会是April_,只能是APRIL(ucase),所以请交换代码
For Each NamedRange In ActiveWorkbook.Names
If UCase(Left(NamedRange.Name, 6)) = "APRIL_" Then
Range(NamedRange.RefersTo).EntireRow.Hidden = False
End If
Next NamedRange
答案 1 :(得分:0)
请参阅下文。
Sub April_button_Click()
Dim NamedRange As Name
For Each NamedRange In ThisWorkbook.Names
'get value for sheet reference
SheetValue = Split(Split(CStr(NamedRange), "!", -1)(0), "=", -1)(1)
'
If UCase(Left(ThisWorkbook.Sheets(SheetValue).Range(NamedRange).Value, 6)) = "APRIL_" Then
ThisWorkbook.Sheets(SheetValue).Range(NamedRange).EntireRow.Hidden = False
End If
Next NamedRange
End Sub
答案 2 :(得分:0)
这是您的代码:
Sub April_button_Click()
Dim NamedRange As Name
For Each NamedRange In ThisWorkbook.Names
If Len(NamedRange.Name) >= 6 And UCase(Left(NamedRange.Name, 6)) = "APRIL_" Then
NamedRange.EntireRow.Hidden = False
End If
Next NamedRange
End Sub
如果我们像这样展开并添加一些教育性注释,可能会更容易阅读:
Sub April_button_Click()
Dim NamedRange As Name
Dim ws As Worksheet
Dim nameRng As Range
For Each NamedRange In ThisWorkbook.Names
' To avoid any errors from the LEFT function, we add a Len-check to make sure we only call
' LEFT if the name is long enough to contain what we are looking for
If Len(NamedRange.Name) >= 6 And UCase(Left(NamedRange.Name, 6)) = "APRIL_" Then
' First we find what worksheet we "need" to qualify our call with
' We do this by asking the named range what is the index of the worksheet the range it
' contains
Set ws = ThisWorkbook.Worksheets(NamedRange.RefersToRange.Worksheet.Index)
' Second we find what the local range is
' We do this by asking the named range what local range it contains
Set nameRng = ws.Range(NamedRange.RefersToRange.Address)
' Now we can just use our range from before:
nameRng.EntireRow.Hidden = False
' Which means the same as this:
ThisWorkbook.Worksheets(NamedRange.RefersToRange.Worksheet.Index).Range(NamedRange.RefersToAddress).EntireRow.Hidden = False
' And you'll notice that all the declarations in the previous line come from NamedRange itself
' That's because NamedRange is already fully qualified!
' So the above statement is equal to this also:
NamedRange.EntireRow.Hidden = False
End If
Next NamedRange
End Sub
绊倒您原始代码的原因是错误地使用了UCASE
。 UCASE
会将其整个参数转换为大写,因此UCase("april_")
不会成为April_
,而是会变成APRIL_
。您的代码正在执行比较"APRIL_ = April_"
,该比较返回False
。