[英]My vba for next loop code using variables is taking too long
New to vba and just starting loops. vba 新手,刚开始循环。 My for next loop code is missing something.我的 for next 循环代码丢失了一些东西。 I have large data sets to audit and part of my macro I'm using simple if then statements with true/false answers if cells match.我有大量数据集要审计,我的宏的一部分我使用简单的 if then 语句,如果单元格匹配,则带有真/假答案。 Currently there are 43 columns and could be up to 70k rows.目前有 43 列,最多可达 70k 行。 I am currently using the following for each of the 43 columns:我目前对 43 列中的每一列使用以下内容:
ActiveCell.FormulaR1C1 = "=IF(RC[-2]=RC[-1],TRUE,FALSE)"
ActiveCell.AutoFill Range(ActiveCell, ActiveCell.Offset(0, -7).End(xlDown).Offset(0, 7))
I wanted to simplify my code and hopefully speed up the macro with the code below.我想简化我的代码,并希望用下面的代码加速宏。 Both ways work, but this second way takes longer for some reason.两种方式都有效,但由于某种原因,第二种方式需要更长的时间。 I have tested and can see the values populate immediately but then I just get a wait cursor for about a minute.我已经测试过并且可以看到值立即填充,但随后我只得到一个等待光标大约一分钟。 Can someone tell me why the application is thinking for so long after the values are in??有人能告诉我为什么应用程序在值输入后考虑这么久吗??
Dim lastrow As Long
lastrow = Range("a" & Rows.Count).End(xlUp).Row
Dim i As Long
Dim x As Integer
For i = 3 To lastrow
For x = 5 To 134 Step 3
For Each cell In Cells(i, x)
If cell.Offset(0, -2).Value = cell.Offset(0, -1).Value Then
cell.Value = True
Else
cell.Value = False
End If
Next cell
Next x
Next i
One should always include the parent sheet to any Range object, this practice will help when the code begins to get more complicated.应该始终将父工作表包含到任何 Range 对象中,当代码开始变得更复杂时,这种做法将有所帮助。
Use Variant array when iterating.迭代时使用 Variant 数组。 You are literally making hundreds or even thousands of trips back and forth between the sheet and vba code.您实际上是在工作表和 vba 代码之间来回往返数百甚至数千次。 Every time you do that it slows down the code a little.每次这样做都会使代码变慢一点。
With Worksheets("Sheet1")
Dim lastrow As Long
lastrow = .Range("a" & Rows.Count).End(xlUp).Row
Dim rngArr As Variant
rngArr = .Range("C3:ED" & lastrow).Value
Dim i As Long
For i = LBound(rngArr, 1) To UBound(rngArr, 1)
Dim x As Long
For x = LBound(rngArr, 2) + 2 To UBound(rngArr, 2) Step 3
rngArr(i, x) = rngArr(i, x - 2) = rngArr(i, x - 1)
Next x
Next i
.Range("C3:ED" & lastrow).Value = rngArr
End With
Since Scott tackled the second variation, I thought I'd offer a slight update to the first one由于 Scott 处理了第二个变体,我想我会对第一个变体进行一些更新
Sub option1()
ActiveCell.FormulaR1C1 = "=EXACT(RC[-2],RC[-1])"
ActiveCell.AutoFill Range(ActiveCell, Cells(ActiveCell.Offset(0, -1).End(xlDown).row, ActiveCell.Column))
End Sub
I changed the formula that you were using to the EXACT
function because that's what you recreated using IF
, and I also adjusted the column offsets for when you AutoFill
because they seemed unusual.我将您使用的公式更改为EXACT
函数,因为这是您使用IF
重新创建的公式,并且我还调整了AutoFill
时的列偏移量,因为它们看起来不寻常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.