excel - 在一个非常大的表中循环一个 if 函数。太慢了

标签 excel vba loops if-statement

我有一张很大的 table 。 700,000 行。为了获得我需要的信息,我需要添加一个接收简单 if 或函数的列。
问题是,它太慢了。它在 60 秒内只计算了 7000 行。我需要70万...
使用常规的 excel 函数,它可以在几秒钟内工作。必须有办法用 VBA 做到这一点。
谢谢!!

这是我的代码:

Private Sub CommandButton3_Click()
    Sheet1.Cells(1, 6) = "C & O"

     'count rows
    Dim count As Long
    For i = 1 To 1000000
        If Sheet1.Cells(i, 1) <> "" Then
            count = count + 1
       Else: Exit For
        End If
    Next

    'Fill in coulmn F
    For K = 2 To count
        If (Sheet1.Cells(K, 4) = 651 Or Sheet1.Cells(K, 4) = 652 Or Sheet1.Cells(K, 4) = 653 Or Sheet1.Cells(K, 4) = 805 Or Sheet1.Cells(K, 4) = 806 Or Sheet1.Cells(K, 4) = 808 Or Sheet1.Cells(K, 4) = 804 Or Sheet1.Cells(K, 4) = 807 Or Sheet1.Cells(K, 4) = 809 Or Sheet1.Cells(K, 4) = 810) Then
            Sheet1.Cells(K, 6) = "Oversize"
        Else
            Sheet1.Cells(K, 6) = Sheet1.Cells(K, 5)
        End If
    Next
End Sub

最佳答案

简单的优化可能是只读取一次 Cell 内容(这很慢):

Dim k4
For K = 2 To count
    k4 = Sheet1.Cells(K, 4) 
    If (k4 = 651 Or k4 = 652 Or k4 = 653 Or k4 = 805 Or k4 = 806 Or k4 = 808 Or k4 = 804 Or k4 = 807 Or k4 = 809 Or k4 = 810) Then
        Sheet1.Cells(K, 6) = "Oversize"
    Else
        Sheet1.Cells(K, 6) = Sheet1.Cells(K, 5)
    End If
Next

如果这还不够,那么可能需要转换为数组。

关于excel - 在一个非常大的表中循环一个 if 函数。太慢了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44644863/

相关文章:

php - 带类别过滤器的 Woocommerce 产品循环

python - 如何从当前循环访问循环中的下一个字典值?

excel - 如何将 .xlsx 文件转换为 .CSV 文件,维护可点击的链接

ASP Classic 中的 Excel ADO - 返回第 2 行作为标题

excel - 如何从数据VBA创建下拉列表

c++ - 在 C++ 作业问题中测试字符串输入时无法退出 while 循环(作为数据验证)

excel - DialogSheets ("Name").Labels.Visible = True 不适用于 Excel VBA 中的所有 DialogSheets

excel - Excel 密码保护的 Powershell 测试

vba - 是否可以将 Excel 宏与文件扩展名相关联?

Excel 2007 将工作表另存为 CSV 与在 VBA 中将工作表另存为 csv 不同