加速excel格式化vba代码?

0 excel vba excel-vba

我使用以下vba代码将文本字符串日期更改为excel中的实际日期,因此我可以将其用于逻辑比较等.

问题是我需要这个工作大约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
Run Code Online (Sandbox Code Playgroud)

有没有其他方法可以更快地做同样的事情?我假设它是如此缓慢的一部分原因是因为选择单个单元格并反复处理代码所涉及的开销但我不知道如何以其他方式执行此操作?

底部的一些行还包含"未指定"字样,当代码到达这些单元格时,它会断开

运行时错误'13':类型不匹配

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

ass*_*ias 6

第一步是:

  • 关闭屏幕更新
  • 关闭计算
  • 一次读取和写入范围

它可能看起来像下面的代码 - 最好包含一个错误处理程序,以避免关闭屏幕更新或更改计算模式的电子表格:

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
Run Code Online (Sandbox Code Playgroud)