2016-12-04 61 views
1

看我下面的代碼:是沒有什麼問題的VBA

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是沒有(空)的錯誤彈出,即使是我想要做什麼。 「錯誤91.對象或變量或帶塊變量未設置任何人都知道爲什麼感謝

回答

3

不指定在哪一行程序崩潰我以爲這是?!

If rgn = f Then 

=操作比較兩個變量是否相等,如果左邊和/或右邊是一個對象,則比較對象的內容是否相等,所以這個變量是取消引用,這對於什麼也不是不起作用,因爲它什麼都不引用。你想要的是比較身份,即檢查兩個對象變量引用同一個對象。爲此,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 
相關問題