我试图遍历大约2000行的数据,并执行for循环和每个循环中的多个if语句。它可以工作,但现在速度很慢。从我的研究中可以了解到,如果我可以将数据放入数组中并在其中进行处理,然后再将数据放回单元中,则速度会更快,但是我可以在编码方面使用一些帮助。这是我的代码。
Sub EliminateVariance()
Dim Old As Long
Dim Older As Long
Dim Oldest As Long
Dim Current As Long
Dim VarianceOld As Long
Dim VarianceNew As Long
Dim VarianceNew1 As Long
Dim VarianceNew2 As Long
Dim Month1 As Variant
Dim SheetName As Variant
Dim LastRow As Long
Dim i As Long
Month1 = InputBox("What is this month?")
SheetName = Month1 & " SummaryByCust"
Worksheets(SheetName).Activate
LastRow = Cells(Rows.count, "B").End(xlUp).row
For i = 3 To LastRow
VarianceOld = Range("V" & i)
Oldest = Range("I" & i)
Older = Range("H" & i)
Old = Range("G" & i)
Current = Range("F" & i)
If VarianceOld > Oldest Then
VarianceNew = VarianceOld - Oldest
Range("I" & i) = 0
If VarianceNew > Older Then
VarianceNew1 = VarianceNew - Older
Range("H" & i) = 0
If VarianceNew1 > Old Then
VarianceNew2 = VarianceNew1 - Old
Range("G" & i) = 0
If VarianceNew2 > Current Then
MsgBox ("Error: Deferred is greater than what it should be. Verify your numbers")
Else
Range("F" & i) = Current - VarianceNew2
End If
Else
Range("G" & i) = Old - VarianceNew1
End If
Else
Range("H" & i) = Older - VarianceNew
End If
Else
Range("I" & i) = Oldest - VarianceOld
End If
Next i
End Sub
答案 0 :(得分:1)
以下是有关如何使用数组的示例:
Sub arrayEx()
'Set the range
Dim rng As Range
Set rng = Worksheets("Sheet1").Range("A1:B20000")
'Bulk load the values from the range into an array
'Even if a single column this will create a 2D array
Dim rngArr As Variant
rngArr = rng.Value
'Loop the "Rows" of the array
Dim i As Long
For i = LBound(rngArr, 1) To UBound(rngArr, 1)
'Do something with that array
'when loaded from a range it is similar nomenclature to Cells: array(row,column)
If rngArr(i, 1) = "A" Then
rngArr(i, 2) = "B"
End If
Next i
'overwrite the values in range with the new values from the array.
rng.Value = rngArr
End Sub
尝试适应您的需求。