VBA用For循环设置单元格格式,运行速度慢
VBA用For循环设置单元格格式,运行速度慢。特别是当要设置的函数很多的时候,比如6000行,刚开始的时候速度还可以,可是都后面(大概处理到40%行时,速度就骤降下来,有什么办法可以优化呢! 代码如下For i = 2 To ixRefNo Step 1
With strWS.Range("B" & i & ":AE" & i)
.FormatConditions.Delete
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=OR($A$" & i & "=""BAD"", $A$" & i & "=""TOBE"")"
.FormatConditions(1).Font.ColorIndex = 3
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$A$" & i & "=""SKIP"""
.FormatConditions(2).Font.ColorIndex = 15
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$A$" & i & "=""OK"""
.FormatConditions(3).Font.ColorIndex = 1
.Font.Bold = True
End With
iProcess = Round((i - 1) / ixRefNo * 100)
Application.StatusBar = "Formating Sheet '" & strWS.Name & "', " & iProcess & "% Complete"
Next --------------------编程问答-------------------- 开始的时候 加上 Application.ScreenUpdating = False
结束的时候 加上 Application.ScreenUpdating = true
--------------------编程问答-------------------- 小小的看法:能不能选选择这些单元格,再一次设置格式…… --------------------编程问答-------------------- 为什么要使用For来呢?
看看这个自己录制的宏,设置了近200行单元格的格式,也就这点代码而已。
--------------------编程问答-------------------- 连续区域????
Sub Macro1()
'
' Macro1 Macro
' ºêÓÉ Î¢ÈíÓû§ ¼ÖÆ£¬Ê±¼ä: 2012-3-21
'
'
Rows("2:186").Select
Selection.NumberFormatLocal = "@"
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
With Selection.Font
.Name = "ËÎÌå"
.FontStyle = "³£¹æ"
.Size = 10
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ColorIndex = xlAutomatic
End With
End Sub
还有你条件格式为什么行和列都用$
在EXCEL的VBE窗口运行下列程序试试
Sub cccc()
Dim ixRefNo As Long
Dim i As Long
ixRefNo = 65535
i = 2
With Sheets("Sheet1").Range("B" & i & ":AE" & i)
.FormatConditions.Delete
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=OR($A" & i & "=""BAD"", $A" & i & "=""TOBE"")"
.FormatConditions(1).Font.ColorIndex = 3
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$A" & i & "=""SKIP"""
.FormatConditions(2).Font.ColorIndex = 15
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$A" & i & "=""OK"""
.FormatConditions(3).Font.ColorIndex = 1
.Font.Bold = True
End With
Sheets("Sheet1").Range("B" & 3 & ":AE" & ixRefNo).FormatConditions.Delete
Sheets("Sheet1").Range("B2:AE2").AutoFill Destination:=Sheets("Sheet1").Range("B2:AE" & ixRefNo), Type:=xlFillDefault 'xlFillFormats
End Sub --------------------编程问答--------------------
速度是可以了,但是出现错行了,
例如第21行的format condition 是=OR($A65519="BAD", $A65519="TOBE")
补充:VB , VBA