使用vba慢单元格格式?

免责声明:我是相对较新的VBA和macros。

我已经写了一个macros来更新一些单独的单元格中的值和格式,通过http读取和parsing一个json,并且这个过程非常缓慢,所以我把代码分解成不同的部分来查看瓶颈可能在哪里。 原来的单元格更新是问题,我有以下代码:

Sub test() Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Application.EnableEvents = False Application.EnableCancelKey = False t = Timer With Range("A1") .Font.Italic = True .Interior.ColorIndex = 37 .Value = 3412 End With Debug.Print Timer - t Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic Application.EnableEvents = True Application.EnableCancelKey = True End Sub 

debugging打印大约0.3到0.5秒…我之后进一步包围每个italiccolorIndexvalue线的计时器,他们都变成大约每个0.015秒…我试过在线search如何使代码更有效率,因此screenupdating切换以及不selection ,但0.5秒仍然有点慢,更新一个单元给我。

请注意,我不是在抱怨,我只是想知道我是否在这里做正确的事情。 有没有更有效的方法来实现我在这里发布的格式和值的变化,还是只是一个事实,Excel需要这么多的时间来更新单元格? 我只是很好奇,因为我也实现了json的阅读和parsing,比这更快。

另外,我已经在至less3台电脑上testing了这个脚本,并且它们都在同一时间,所以我不认为这是个人电脑问题。 我用Excel 2007和2010来testing。

我假设你想格式化多个单元格? 如果是这样,创build一个范围引用到所有需要相同格式的单元格(它不需要是连续的)将会更快,然后在一个步骤中将所需格式应用到该范围对象

下面的示例演示创build范围引用,并一次性应用格式

 Option Explicit Private Declare Function GetTickCount Lib "kernel32" () As Long Sub Demo() Dim t As Long Dim n As Long, i As Long Dim m As Long Dim ws As Worksheet Dim cl As Range Dim rSearch As Range Dim rResult As Range Set ws = ActiveSheet ' or another sheet... Set rSearch = ws.Range("A1:A1000") ' note, this is an inefficient loop, can be made much faster ' details will depend on the use case For Each cl In rSearch ' determine if cell is to be formatted If cl.Row Mod 2 = 0 Then ' add cl to Result range If rResult Is Nothing Then Set rResult = cl Else Set rResult = Application.Union(rResult, cl) End If End If Next Debug.Print "Result Range includes ", rResult.Cells.Count, "Cells" t = GetTickCount ' Apply format With rResult .Font.Italic = True .Interior.ColorIndex = 37 .Value = 3412 End With Debug.Print (GetTickCount - t) / 1000, "seconds" End Sub