查看下面的代码:
Sub AdvencedFilterNew()
'
' AdvencedFilterNew Macro
'
Dim WsOutput As Worksheet
Dim WsMain As Worksheet
Dim wsScenarios As Worksheet
Dim ScenarioIDrow As Long
Dim ScenarioIDColumn As Long
Dim rgn As Range
Dim p As String
Dim q As String
Dim f As Range
Set WsOutput = Worksheets("Output")
Set WsMain = Worksheets("Main Menu")
Set wsScenarios = Worksheets("Scenarios.New")
WsOutput.Activate
Cells.EntireColumn.Hidden = False
WsMain.Activate
Range("E15").Select
Range("E17:Q350").AdvancedFilter Action:=xlFilterInPlace, CriteriaRange:= _
Range("E14:Q15"), Unique:=False
ScenarioIDrow = WsOutput.Cells.Find("Scenario ID").Row
ScenarioIDColumn = WsOutput.Cells(ScenarioIDrow, Columns.Count).End(xlToLeft).Column
p = wsScenarios.Cells(ScenarioIDrow, 2).Address(RowAbsolute:=False, ColumnAbsolute:=False)
q = wsScenarios.Cells(ScenarioIDrow, ScenarioIDColumn).Address(RowAbsolute:=False, ColumnAbsolute:=False)
WsOutput.Activate
WsOutput.Range(p, q).Select
Set f = Selection.Find(What:=Worksheets("Main Menu").Range("E15").Value, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False)
For Each rgn In Selection
If rgn = f Then
rgn.EntireColumn.Hidden = False
ElseIf f Is Nothing Then
rgn.EntireColumn.Hidden = False
Else
rgn.EntireColumn.Hidden = True
End If
Next rgn
WsMain.Activate
WsMain.Range("E15").Select
所以,它工作正常但是当我的范围(e15)= f没什么(blanK)时会弹出一个错误,即使它做了我想要的。 "错误91.对象或变量或未设置块变量。谁知道为什么?谢谢!
答案 0 :(得分:3)
您没有指定程序崩溃的行。我假设它是:
If rgn = f Then
=
运算符比较两个变量是否相等。如果左侧和/或右侧是对象,则比较对象的内容是否相等。所以变量是解除引用。 Nothing 不会起作用,因为它没有引用任何东西。
你想要的是比较身份,即检查两个对象变量是否引用同一个对象。为此,Visual Basic和VBA具有IS
运算符。
因此,要修复它,您可以将行更改为:
If rgn = f Then
或者您只需将语句的顺序重新排列为:
If f Is Nothing Then
rgn.EntireColumn.Hidden = False
ElseIf rgn = f Then
rgn.EntireColumn.Hidden = False
Else
rgn.EntireColumn.Hidden = True
End If