【问题标题】:How to reduce runtime for code using ranges and string comparisons如何使用范围和字符串比较来减少代码的运行时间
【发布时间】:2012-11-16 19:59:07
【问题描述】:

我有以下代码,它完全符合我的需要,但是,循环运行时间太长(3 分钟以上)。我是 VBA 的新手,所以我不确定 1)最好的替代方案是什么 2)如何为该替代方案使用正确的语法并让我的代码完美运行。谢谢!

Dim i As Integer
For i = 2 To 13000

If Sheets("Sheet1").Range(Cells(i, 3), Cells(i, 3)) = "Police" 
    And Sheets("Sheet1").Range(Cells(i, 14), Cells(i, 14)) = "Bi-wkly Uniform Pay" Then _
Sheets("Sheet1").Range(Cells(i, 3), Cells(i, 3)) = "Police - Uniform"

Next i

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    在循环中访问工作表非常慢。更好的方法是将数据复制到Variant,数组循环遍历数组,然后将结果复制回工作表

    类似这样的:

    Sub Demo()
        Dim i As Long
        Dim datCol3 As Variant
        Dim datCol14 As Variant
    
        With Sheets("Sheet1")
            ' Copy data into a Variant Array
            datCol3 = .Range(.Cells(1, 3), .Cells(13000, 3)).Formula
            datCol14 = .Range(.Cells(1, 14), .Cells(13000, 14)).Value
            ' Loop over the array
            For i = 2 To 13000
                If datCol3(i, 1) = "Police" And datCol14(i, 1) = "Bi-wkly Uniform Pay" Then
                    datCol3(i, 1) = "Police - Uniform"
                End If
            Next
            'Return the results to the sheet
            .Range(.Cells(1, 3), .Cells(13000, 3)).Formula = datCol3
        End With
    End Sub
    

    【讨论】:

    • 很高兴为您提供帮助。如果它解决了你的问题,你应该accept an answer
    【解决方案2】:

    这可能不是最佳答案,但请尝试设置局部变量

    Var sht1 = Sheets("Sheet1") 可能会稍微减少对工作表对象的选择。此外,没有必要使用 (i, 3) 选择范围和单元格,因为它是单个单元格的范围,所以结合起来你会有类似的东西

     If sht1.Range.Cells(i,3) = "Police" And sht1.Range.Cells(i,14) = "Bi-wkly Uniform Pay" Then sh1.Range.Cells(i,3) = "Police Uniform" 
    Next i
    

    如果这不起作用并且您可以将它放在不同的列中(例如列 O 或 15),那么您只需使用一个公式,然后拖动/双击,或者您可以在整个列中使用一个数组公式列类似,然后按 ctrl + shift + enter 使其计算为数组公式。

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      建议 1

      替换:

      If Sheets("Sheet1").Range(Cells(i, 3), Cells(i, 3)) = "Police" 
          And Sheets("Sheet1").Range(Cells(i, 14), Cells(i, 14)) = "Bi-wkly Uniform Pay" Then _
        Sheets("Sheet1").Range(Cells(i, 3), Cells(i, 3)) = "Police - Uniform"
      

      作者:

      With Sheets("Sheet1")
        If .Range(Cells(i, 3), Cells(i, 3)) = "Police" _
            And .Range(Cells(i, 14), Cells(i, 14)) = "Bi-wkly Uniform Pay" Then _
          .Range(Cells(i, 3), Cells(i, 3)) = "Police - Uniform"
      End With
      

      建议 2

      替换:

      .Range(Cells(i, 3), Cells(i, 3))
      

      .Cells(i, 3)
      

      建议 3

      添加:

      Application.ScreenUpdating = False
      

      如果没有此声明,则每次更改都会重新绘制屏幕。这比其他任何事情都耗费更多时间。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 2018-05-07
        • 2016-07-18
        相关资源
        最近更新 更多