2012-06-16 122 views
1

我有一個宏,遍歷一些行,在相關圖表中更新數據點的着色。這些行可以被用戶隱藏,因此它檢查隱藏值,即Excel的VBA優化隱藏的行

Do While wsGraph.Cells(RowCounter, 1) <> "" 
    If wsGraph.Rows(RowCounter).Hidden = False Then 
     'code here 
    End If 
    RowCounter = RowCounter + 1 
Loop 

該代碼需要69秒運行。如果我對隱藏行進行測試,則需要1秒鐘才能運行。

有沒有更好的辦法做這個測試,否則,我會告訴他們的用戶不能使用隱藏功能(或處理69秒的延遲)。

感謝


下面是完整的代碼,如要求。

該圖是一幅柱狀圖,和餘顏色基於該值在一定範圍內是,例如點:超過75%=綠色,超過50%=黃色,超過25%=橙,否則紅色。表單上有一個按鈕,用於重新着色圖表,執行此代碼。

如果有人對數據進行過濾表,發生的事情是這樣的:說的第20行均超過75%,而最初綠色。在過濾表格後,假設只有前5個超過75%。該圖仍然顯示前20個爲綠色。所以這個帶宏的按鈕重新調色吧。

' --- set the colour of the items 
Dim iPoint As Long 
Dim RowCounter As Integer, iPointCounter As Integer 
Dim wsGraph As Excel.Worksheet 
Set wsGraph = ThisWorkbook.Worksheets(cGraph5) 
wsGraph.ChartObjects("Chart 1").Activate 
' for each point in the series... 
For iPoint = 1 To UBound(wsGraph.ChartObjects("Chart 1").Chart.SeriesCollection(1).Values) 
    RowCounter = 26 
    iPointCounter = 0 
    ' loop through the rows in the table 
    Do While wsGraph.Cells(RowCounter, 1) <> "" 
     ' if it's a visible row, add it to the counter, if it's the same counter as in the series, exit do 
     If wsGraph.Rows(RowCounter).Hidden = False Then 
      iPointCounter = iPointCounter + 1 
      If iPointCounter = iPoint Then Exit Do 
     End If 
     RowCounter = RowCounter + 1 
    Loop 
    ' colour the point from the matched row in the data table 
    Dim ColorIndex As Integer 
    If wsGraph.Cells(RowCounter, 5) >= 0.75 Then 
     ColorIndex = ScoreGreen 
    ElseIf wsGraph.Cells(RowCounter, 5) >= 0.5 Then 
     ColorIndex = ScoreYellow 
    ElseIf wsGraph.Cells(RowCounter, 5) >= 0.25 Then 
     ColorIndex = ScoreOrange 
    ElseIf wsGraph.Cells(RowCounter, 5) >= 0 Then 
     ColorIndex = ScoreRed 
    Else 
     ColorIndex = 1 
    End If 
    ActiveChart.SeriesCollection(1).Points(iPoint).Interior.ColorIndex = ColorIndex 
Next 
+0

別的事情必須發生從1秒跳到69秒的時間;你的循環將只執行'here'如果行(RowCounter)是隱藏的代碼 - 您可以爲'代碼here'一些細節? – whytheq

+0

@whytheq:如果我有過濾/沒有行隱藏在數據表,然後我用了「隱藏」複選框註釋掉運行它,它是相同的有效結果。對於279個數據錶行,時間差異在1秒和23秒之間。 – Sean

回答

2

嘗試Special Cells

Sub LoopOverVisibleCells() 
    Dim r As Range 
    Dim a As Range 
    dim cl As Range 

    Set r = ActiveSheet.UsedRange.Columns(1).SpecialCells(xlCellTypeVisible) 

    For Each a In r.Areas 
     For Each cl In a 
      ' code here 
     Next 
    Next 

End Sub 
0

這是我做了什麼,用克里斯的建議。它沒有回答爲什麼隱藏的檢查是如此緩慢,但它是做recolouring的更有效的方法:

Dim myrange As range 
Set myrange = wsGraph.range("E26:E304").SpecialCells(xlCellTypeVisible) 
Dim i As Integer 
For i = 1 To myrange.Rows.Count 
    If myrange.Cells(i, 1) >= 0.75 Then 
     ColorIndex = ScoreGreen 
    ElseIf myrange.Cells(i, 1) >= 0.5 Then 
     ColorIndex = ScoreYellow 
    ElseIf myrange.Cells(i, 1) >= 0.25 Then 
     ColorIndex = ScoreOrange 
    ElseIf myrange.Cells(i, 1) >= 0 Then 
     ColorIndex = ScoreRed 
    Else 
     ColorIndex = 1 
    End If 
    ActiveChart.SeriesCollection(1).Points(i).Interior.ColorIndex = ColorIndex 
Next i