2012-06-08 61 views
0

當E列中的單元格值等於0(零)時,我試圖自動隱藏/取消隱藏相應的行。這些單元格中有公式,當另一個單元格發生更改時,這些公式將返回零。在這個變化之後,我希望代碼執行隱藏/取消隱藏的魔法。單元格值= 0時隱藏相應的行

非常感謝。

回答

0

使用此mhetod:

Sub HideRows() 
Dim i As Integer 
i = 1 
Do While Not Cells(i, 5) = "" 
    If Cells(i, 5).Value = 0 Then 
     Rows(CStr(i) + ":" + CStr(i)).EntireRow.Hidden = True 
    ElseIf Cells(i, 5).Value <> 0 And Rows(CStr(i) + ":" + CStr(i)).EntireRow.Hidden = True Then 
     Rows(CStr(i) + ":" + CStr(i)).EntireRow.Hidden = False 
    End If 
i = i + 1 
Loop 
End Sub 

可以在Microsoft Excel中添加一個按鈕,並通過Button_Click事件調用此方法或添加下一個方法在必要對象

Private Sub Worksheet_Change() 
    Module1.HideRows 
End Sub 

這方法將在某個單元更改時調用HideRow方法。

1

這是使用AutoFilter的更快速的方法。您可以直接調用此代碼或在Worksheet_Calculate事件中使用它。我假設Cell E1有頭文件。

在按鍵

Option Explicit 

Sub Sample() 
    Dim rRange As Range, RngToHide As Range 
    Dim lRow As Long 

    '~~> Remove any filters 
    ActiveSheet.AutoFilterMode = False 

    With Sheets("Sheet1") 
     lRow = .Range("E" & Rows.Count).End(xlUp).Row 
     Set rRange = .Range("E1:E" & lRow) 

     With rRange 
      .AutoFilter Field:=1, Criteria1:="0" 
      Set RngToHide = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow 
     End With 
    End With 

    '~~> Remove any filters 
    ActiveSheet.AutoFilterMode = False 

    If Not RngToHide Is Nothing Then RngToHide.Hidden = True 
End Sub 

工作表計算事件 - 不推薦

我不建議自動調用這個代碼,因爲這會不會讓你取消隱藏的情況下,各行要改變隱藏行中的內容。要取消隱藏行,您必須將Worksheet_Calculate事件中的整個代碼註釋掉,或者將連接單元格中的值更改爲非零值(提供連接的單元格不在隱藏行中)。

這將隱藏的行時山口E中的值更改爲0

Option Explicit 

Private Sub Worksheet_Calculate() 
    Dim rRange As Range, RngToHide As Range 
    Dim lRow As Long 

    On Error GoTo Whoa 

    Application.ScreenUpdating = False 
    Application.EnableEvents = False 

    '~~> Remove any filters 
    ActiveSheet.AutoFilterMode = False 

    With Sheets("Sheet1") 
     lRow = .Range("E" & Rows.Count).End(xlUp).Row 
     Set rRange = .Range("E1:E" & lRow) 

     With rRange 
      .AutoFilter Field:=1, Criteria1:="0" 
      Set RngToHide = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow 
     End With 
    End With 

    '~~> Remove any filters 
    ActiveSheet.AutoFilterMode = False 

    If Not RngToHide Is Nothing Then RngToHide.Hidden = True 

LetsContinue: 
    Application.ScreenUpdating = True 
    Application.EnableEvents = True 
    Exit Sub 
Whoa: 
    MsgBox Err.Description 
    Resume LetsContinue 
End Sub