加快Excel格式化VBA代码?

我正在使用下面的VBA代码将文本stringdate更改为在Excel中的实际date,所以我可以使用它进行逻辑比较等。

问题是我需要这个工作约4000行,每周更新,这个代码是非常缓慢的。

Sub Datechange() Dim c As Range For Each c In Range("D2:D" & Range("D" & Rows.Count).End(xlUp).Row) c.Value = CDate(c.Value) Next c End Sub 

有没有其他方法可以更快地做同样的事情? 我假设它是如此缓慢的部分原因是因为select单个单元格和反复处理代码涉及开销,但我不知道如何以任何其他方式做到这一点?

还有一些在底部的行包含单词“无指定”,当代码达到这些细胞打破

运行时错误“13”:types不匹配

有没有办法阻止这种情况发生,所以下面的代码可以完成?

第一步是:

  • closures屏幕更新
  • closures计算
  • 一次读写范围

它可能看起来像下面的代码 – 这是一个好主意,包括一个error handling程序,以避免离开电子表格closures屏幕更新或更改计算模式:

 Sub Datechange() On Error GoTo error_handler Dim initialMode As Long initialMode = Application.Calculation 'save calculation mode Application.Calculation = xlCalculationManual 'turn calculation to manual Application.ScreenUpdating = False 'turn off screen updating Dim data As Variant Dim i As Long 'copy range to an array data = Range("D2:D" & Range("D" & Rows.Count).End(xlUp).Row) For i = LBound(data, 1) To UBound(data, 1) 'modify the array if the value looks like a date, else skip it If IsDate(data(i, 1)) Then data(i, 1) = CDate(data(i, 1)) Next i 'copy array back to range Range("D2:D" & Range("D" & Rows.Count).End(xlUp).Row) = data exit_door: Application.ScreenUpdating = True 'turn screen updating on Application.Calculation = initialMode 'restore original calculation mode Exit Sub error_handler: 'if there is an error, let the user know MsgBox "Error encountered on line " & i + 1 & ": " & Err.Description Resume exit_door 'don't forget the exit door to restore the calculation mode End Sub 

最好是在一个单一的“拉”中获取数组中的值,对数组进行操作并将其写回。 这将绕过昂贵的射程操作。

 dim c as range set c = Range("D2:D" & Range("D" & Rows.Count).End(xlUp).Row) dim ArrValue() as Variant set ArrValue = c.value 

下一步:遍历该数组,然后回写:

 c.value = Arrvalue 

我没有时间来testing代码,所以请自己纠正,我很抱歉。