如何在 excel VBA 中提高用户表单的保存速度

How to improve the saving speed for userform in excel VBA


这是我创建的用户表单。然后,它被用作输入平台。有一些不同的表,例如 2016 年,2017 年......该保存按钮的逻辑是搜索用户输入的年份(日期)并定位正确的工作表。然后,它将找到该工作表的最后一行。

例如,最后一行是第 1000 行。用户表单的第一行将保存在第 1001.The 行,用户表单的第二行将保存在第 1002 行....

问题

但是,当我在真实的excel文件中测试时,保存速度太慢。因为真实的excel文件很大(每个工作表中大约有1XXXX行)。它使用8 sec 为 userform 保存一行,13sec 保存两行。

显然,保存速度是不能接受的。有什么方法可以改善吗?

  If ComboBox3.Value = "2016" Then
    Worksheets("2016").Activate
    j = WorksheetFunction.CountA(Worksheets("2016").Range("A:A")) + 1
    End If
    
    If ComboBox3.Value = "2017" Then
    Worksheets("2017").Activate
    j = WorksheetFunction.CountA(Worksheets("2017").Range("A:A")) + 1
    End If
    
    
    
    '1st
    
    
    
    If ComboBox4.Value = "" Then
    Else
    Cells(j, 1) = ComboBox434.Value
    Cells(j, 5) = ComboBox1.Value
    Cells(j, 4) = ComboBox2.Value
    Cells(j, 3) = ComboBox3.Value
    If ComboBox4.ListIndex <> -1 Then
    Cells(j, 6) = TimeValue(ComboBox4.Value & ":" & ComboBox5.Value)
    Cells(j, 24) = ComboBox4.Value
    Cells(j, 25) = ComboBox5.Value
    Else
    Cells(j, 6) = ""
    End If
    Cells(j, 7) = ComboBox6.Value
    Cells(j, 8) = ComboBox7.Value
    Cells(j, 9) = ComboBox8.Value
    Cells(j, 10) = TextBox2.Value
    Cells(j, 11) = TextBox3.Value
    Cells(j, 12) = TextBox4.Value
    Cells(j, 13) = TextBox5.Value
    Cells(j, 14) = TextBox42.Value
    Cells(j, 15) = TextBox43.Value
    Cells(j, 16) = TextBox44.Value
    Cells(j, 17) = TextBox666.Value
    
    'If ComboBox4.Value = "" Then
    
    End If
    
    '2nd
    
    j = j + 1
    
    If ComboBox9.Value = "" Then
    Else
    Cells(j, 1) = ComboBox434.Value
    Cells(j, 5) = ComboBox1.Value
    Cells(j, 4) = ComboBox2.Value
    Cells(j, 3) = ComboBox3.Value
    If ComboBox9.ListIndex <> -1 Then
    Cells(j, 6) = TimeValue(ComboBox9.Value & ":" & ComboBox10.Value)
    Cells(j, 24) = ComboBox9.Value
    Cells(j, 25) = ComboBox10.Value
    Else
    Cells(j, 6) = ""
    End If
    Cells(j, 7) = ComboBox11.Value
    Cells(j, 8) = ComboBox12.Value
    Cells(j, 9) = ComboBox13.Value
    Cells(j, 10) = TextBox6.Value
    Cells(j, 11) = TextBox7.Value
    Cells(j, 12) = TextBox8.Value
    Cells(j, 13) = TextBox9.Value
    Cells(j, 14) = TextBox45.Value
    Cells(j, 15) = TextBox46.Value
    Cells(j, 16) = TextBox47.Value
    Cells(j, 17) = TextBox617.Value

您可以将计算切换为手动计算,然后在插入信息后计算,这样或许可以节省一些时间。

具体来说,在您的代码开头:

With Application
    .ScreenUpdating = False
    .EnableEvents = False
    .Calculation = xlCalculationManual
End With

在您的代码末尾再次:

With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .Calculation = xlCalculationAutomatic
End With

此外,您可能希望将数据存储在一个变体数组中,它可以一次性全部插入到工作表中,或者存储在一个数组中,然后将 Cells(j,1) 调整为数组的大小

例如

Cells(j, 1).resize(Ubound(arr,1), Ubound(arr,2)) = arr 'Need to check for exact syntax

这可以最大限度地减少工作表被点击的次数。