2012-06-16 82 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