2015-04-23 61 views
1

在Excel中,我有一個元素列表。每一行都有一個顏色。 對於每種顏色,我都會創建一個按鈕來隱藏其他行。Excel VBA - 按顏色比較行時的改進時間

例如,如果我點擊紅色的按鈕,所有不是紅色的行都被隱藏。

而且還有一個復位按鈕,取消隱藏所有行 下面的代碼:

Sub Red_Click() 
    Dim Color_Index As Long 
    Color_Index = Range("I1").Interior.ColorIndex 
    Call HideOther(Color_Index) 
End Sub 

Sub Green_Click() 
Dim Color_Index As Long 
Color_Index = Range("E1").Interior.ColorIndex 
Call HideOther(Color_Index) 
End Sub 

Sub HideOther(Color_Index) 
    Set rRange = Range("$A4:$A313") 
    For Each cl In rRange 
     currentColIndex = cl.Interior.ColorIndex 
     If currentColIndex <> Color_Index Then 
      cl.EntireRow.Hidden = True 
     End If 
    Next cl 
End Sub 

Sub Reset() 
    Cells.EntireRow.Hidden = False 
End Sub 

我比較我的色彩每一行的顏色。

我有300行,所以需要一些時間(約15秒),有沒有辦法來改善時間?我問這是因爲重置/取消隱藏功能是即時的。

我在Excel中的一個初學者,所以也許我沒有看到更容易的解決方案

+3

如果您有Excel 2007或更高版本,你可以通過顏色自動篩選。在做宏時錄製一個宏會給你基本的代碼。 – Rory

+2

在開始時關閉屏幕更新可能會有所幫助。 Application.ScreenUpdating = False(結束時返回true)。 –

+0

此外,您可能會禁用事件並再次啓用它們,禁用自動重新計算並重新啓用它等。 – user3819867

回答

1

正如評論中所說,關閉屏幕更新將有所幫助。根據您的數據,關閉計算也可能有幫助。

除此之外,在速度上的重大改進會立即被隱藏的所有行:

Sub HideOther(Color_Index) 
    Dim cells As Range 

    Set rRange = Range("$A4:$A313") 
    For Each cl In rRange 
     currentColIndex = cl.Interior.ColorIndex 
     If currentColIndex <> Color_Index Then 
      If Not cells Is Nothing Then 
       Set cells = Union(cells, cl) 
      Else 
       Set cells = cl 
      End If 
     End If 
    Next cl 

    cells.EntireRow.Hidden = True 
End Sub 
+0

它完美的作品。謝謝! – jvo

0

我認爲這將是稍快,因爲我少預定義的東西,並用定義的變量(即我不知道是什麼我正在做)。

Sub Red_Click() 
    Dim Color_Index As Long 
    Color_Index = Range("I1").Interior.ColorIndex 
    Call HideOther(Color_Index) 
End Sub 

Sub Green_Click() 
Dim Color_Index As Long 
Color_Index = Range("E1").Interior.ColorIndex 
Call HideOther(Color_Index) 
End Sub 

Sub HideOther(Color_Index As Long) 
    For Each Cell In Range("$A4:$A313")            'why define something when you're 
     If Cell.Interior.ColorIndex <> Color_Index Then Cell.EntireRow.Hidden = True 'using it but once 
    Next 
End Sub 

Sub Reset() 
    Cells.EntireRow.Hidden = False 
End Sub