我的目的是使用Instr
功能检查是否有" x"在命名范围内,如果是,则触发事件以隐藏另一个命名范围。
我的代码无效,显示
错误438"对象不支持此属性或方法"
我尝试将代码更改为
Set rng = Workbooks("Book1.xls").Names("suppliers").RefersToRange
但这也不起作用。
是什么原因?
我的代码:
Sub HideRows()
Dim rng1 As Range, rng2 As Range, c As Range
enter code here
Set rng1 = ActiveWorkbook.Range("suppliers")
Set rng2 = ActiveWorkbook.Range("tohide")
For Each c In rng1
If InStr(1, LCase(rng1), "x") <> 0 Then
rng2.EntireRow.Hidden = True
End If
Next
End Sub
答案 0 :(得分:2)
workbook
没有Range
方法。您只能使用worksheet
对象访问范围。假设命名范围在活动工作表内,您可以使用
Set rng1 = ActiveSheet.Range("suppliers")
Set rng2 = ActiveSheet.Range("tohide")
答案 1 :(得分:2)
试试这个。您在c
循环中没有使用For
。你使用Names
也没问题,所以我已经恢复了。
Option Explicit
Sub HideRows()
Dim rng1 As Range, rng2 As Range, c As Range
Set rng1 = ThisWorkbook.Names("suppliers").RefersToRange
Set rng2 = ThisWorkbook.Names("tohide").RefersToRange
For Each c In rng1
If InStr(1, c.Value, "x", vbTextCompare) > 0 Then
rng2.EntireRow.Hidden = True
End If
Next c
End Sub
答案 2 :(得分:0)
每当另一个范围的单元符合某些标准时,你必须隐藏相同的范围听起来很奇怪
我的意思是我想说你想要隐藏行的隐藏范围相应于检查范围匹配单元格
如下所示
Option Explicit
Sub HideRows()
Dim rng1 As Range, rng2 As Range
Dim iRow As Long
Set rng1 = ThisWorkbook.Names("suppliers").RefersToRange
Set rng2 = ThisWorkbook.Names("tohide").RefersToRange
For iRow = 1 to rng1.Rows.Count
rng2.Rows(iRow).EntireRow.Hidden = InStr(1, rng1.Rows(iRow).Value, "x", vbTextCompare) > 0
Next
End Sub
当然,这假设两个范围具有相同的行数