excel - 计算机因简单代码而窒息。我错过了什么?

标签 excel vba performance loops

此宏在列 B 中搜索“检查”数字 (IsNumeric),当找到时将数字偏移 (0,2),然后用“检查”替换原始单元格中的数字。

当作为规则使用 lastrow 时,它运行得非常慢(尽管如果我将范围设置为整个列,即“B:B”,速度同样慢)。

这两种不同方法之间的唯一区别是 lastrow 规则将“Checks”添加到最后一行,一直沿着列一直向下到工作表的最后一行。我整天都在黑客攻击,通常这样的事情不会让我陷入困境(双关语)。

Sub Move_Checks()
    
    Dim ws1 As Worksheet
    Set ws1 = Sheets("Combined")
   
   Dim lastrow As Long
     lastrow = Cells(Rows.Count, "a").End(xlUp).row
    
   Dim rng1 As Range
    Set rng1 = Range("B:B") 
    
    Dim Cell As Range
    Set Cell = Range("B2" & lastrow)
    
            For Each Cell In rng1
               If IsNumeric(Cell.value) = True Then
                  Cell.Offset(0, 3) = Cell.value
                            
            End If
                        
        Next Cell
     
            For Each Cell In rng1
             If IsNumeric(Cell.value) = True Then
                 Cell.value = "Check"
    
            End If
    
        Next Cell


End Sub

最佳答案

尝试修改后的代码。

您不需要两个循环,您可以一次完成更改。

您的 rng1 变量被设置为整个 B 列。

您几乎将 Cell 变量设置为实际上是正确的 Range,但随后在遍历 时通过将它用作每个单元格的占位符来覆盖它>范围

Sub Move_Checks()
    
    Dim ws1 As Worksheet
    Dim rng1 As Range
    Dim Cell As Range
    Dim lastrow As Long

    Set ws1 = Sheets("Combined")

    lastrow = ws1.Cells(Rows.Count, "a").End(xlUp).row

    Set rng1 = Range("B2:B" & lastrow)
    
    For Each Cell In rng1
        If IsNumeric(Cell.value) = True Then
            Cell.Offset(0, 3) = Cell.value
            Cell.value = "Check"            
        End If               
    Next Cell
     
End Sub

关于excel - 计算机因简单代码而窒息。我错过了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62566797/

相关文章:

python - 如何在excel vba上调用python脚本?

excel - 循环excel vba中的行并获取单元格

java - JConsole 可以嵌入到 Java 应用程序中吗?

c++ - 如何从 dll 中获取没有垃圾的字符串?

excel - 如何使 match() 与 Excel VBA 中的日期一起使用?

vb.net - 传递字符串时的 ByRef 与 ByVal 性能

c# - 除了减少内存使用量之外,C# 静态函数是否比非静态函数执行得更好?

excel - 在 Excel 中分析 66k 行

excel - VBA 提取所有相关数据并排序和验证

excel - 工作表对象声明