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/