vba - 如何优化(或尽可能避免)Excel VBA 中的循环

标签 vba excel

Excel VBA 中涉及选择(以及如何避免它们)和“重”循环的各种问题已在本论坛早些时候讨论过。我想稍微扩展一下。假设我想将某个字符串更改为另一个字符串并对数字数据执行其他操作。考虑以下代码:

Option Explicit
Sub LoopExample()
    Dim rownumber, colnumber As Integer

    ' Step 1: start a loop from a desired position
    For rownumber = 30 To 3000
            For colnumber = 30 To 3000

                ' Step 2: check that the cell is not empty
                If IsEmpty(Cells(rownumber, colnumber).Value) = False Then

                    ' Step 3: change all "Cat" texts to "Dog"
                    If Cells(rownumber, colnumber).Value = "Cat" Then
                        Cells(rownumber, colnumber).Value = "Dog"

                    ' Step 4: if the cell value is numeric...
                    ElseIf IsNumeric(Cells(rownumber, colnumber).Value) Then

                        ' ...check another thing and execute something accordingly
                        If (Cells(rownumber, colnumber).Value) / 2 < 0.5 Then
                            Cells(rownumber, colnumber) = Round(Cells(rownumber, colnumber).Value, 4)
                        Else
                            Cells(rownumber, colnumber) = Round(Cells(rownumber, colnumber).Value, 1)
                        End If

                    End If

                End If
            Next colnumber
    Next rownumber
End Sub

现在,这段代码“完美”地工作,但几乎不是一个有效的代码。我应该通过以下方式对其进行优化:1)首先找到所有包含数据的单元格,2)再次循环遍历这些单元格,3)现在将数据进一步划分为数字和非数字数据,以及 4)执行什么我想要这些数字和非数字范围?还是我应该将其中一些步骤组合在一个循环中?

最佳答案

将完整范围转换为变体(结果是包含 2d 数组的变体)、循环变体数组进行更改然后将变体数组返回到工作表会快几个数量级。

关于vba - 如何优化(或尽可能避免)Excel VBA 中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35372664/

相关文章:

excel - 将多个文件拖放到用户窗体

database - 更新命令只更新第一行 vb.net

excel - 使用VBA删除Excel中的空行

sql-server - 有没有办法在 Excel 2007 中生成唯一标识符(在 SQL Server newid() 中)

excel - 根据后续条件显示或隐藏行

excel - 一次返回一个查找值和不同范围的多个对应值

vba - 我们是否需要为每个子程序创建一个错误处理程序?

VBA - 隐藏行宏限制

string - excel中的iserror公式

regex - 如何在单元格内和循环中使用 Microsoft Excel 中的正则表达式 (Regex)