Speed up excel formatting vba code?

前端 未结 2 1499
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 03:13

I am using the following vba code to change a text string date into an actual date in excel so I can use it for logical comparisons and the like.

The problem is I need t

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-26 03:32

    First steps would be:

    • Turn screen updating off
    • Turn calculation off
    • Read and write the range at once

    It could look like the code below - it is a good idea to include an error handler to avoid leaving your spreadsheet with screen updates off or with the calculation mode changed:

    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
    

提交回复
热议问题