早先在此论坛上讨论了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)执行什么操作我想要这些数字和非数字范围吗?还是应该将其中一些步骤组合成一个循环?
我认为您可以通过让Excel仅查看具有值的单元格来进行很多优化。为此,可以SpecialCells
对常量和公式使用的组合-我认为两者的组合将捕获所有“填充”或非空白的单元格:
Sub LoopExample()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim r, s As Range
Set r = Application.Union(ws.UsedRange.SpecialCells(xlCellTypeConstants), _
ws.UsedRange.SpecialCells(xlCellTypeFormulas))
For Each s In r
If s.Row >= 30 And s.Row <= 3000 And s.Column >= 30 And s.Column <= 3000 Then
If s.Value2 = "Cat" Then
s.Value2 = "Dog"
End If
End If
Next s
End Sub
我没有列出评估单元的所有逻辑,但是您明白了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句