Excel中使用VBA的比较方法更快

我的程序从每个文件导入设置到它自己的列中,然后循环遍历所有导入的列,每次一行,以比较每行中的数据。

如果行中每列的所有单元格都相等,则我设置结果列,将行设置为OK,否则,选中以标记它们不是全部相等。

问题是填充结果列需要很长时间,有没有更快的方法? 这是我的代码:

'Auto compare settings and find -1's For i = 6 To 46 If Cells(3, i).Value = "Unit" Then foundcoltodel = i Exit For End If Next i If foundcoltodel > 6 Then Range(Cells(1, 6), Cells(1, foundcoltodel - 1)).EntireColumn.Select End If 'auto compare settings from files imported Dim comparelines() As Integer Dim LastCol As Integer With ActiveSheet LastCol = .Cells(3, .Columns.Count).End(xlToLeft).Column End With Sum = 0 For Each col In Selection.Columns Sum = Sum + 1 Next ReDim comparelines(1 To Sum) z = 1 For Each col In Selection.Columns comparelines(z) = col.Column z = z + 1 Next 'Set row 4 back to black Rows("4:4").Select With Selection.Font .ThemeColor = xlThemeColorLight1 .TintAndShade = 0 End With For i = 7 To 252 If Cells(i, comparelines(1)).Value <> "" Then For j = 1 To Sum 'set compare columns to red Cells(4, comparelines(1)).Select With Selection.Font .Color = -16776961 .TintAndShade = 0 End With Cells(4, comparelines(j)).Select With Selection.Font .Color = -16776961 .TintAndShade = 0 End With 'check for equal values per row in each selected column If Cells(i, comparelines(1)).Value <> Cells(i, comparelines(j)).Value Then allnotequal = True Exit For Else allnotequal = False End If Next j If allnotequal = True And Cells(i, 5).Value <> "" Then Cells(i, LastCol - 2).Value = "Check" Cells(i, LastCol - 2).HorizontalAlignment = xlCenter Cells(i, LastCol - 2).Font.Bold = True End If If allnotequal = False And Cells(i, 5).Value <> "" Then Cells(i, LastCol - 2).Value = "Ok" Cells(i, LastCol - 2).HorizontalAlignment = xlCenter Cells(i, LastCol - 2).Font.Bold = True End If End If Next i 

1

我不会指出每一个实例,但这些事情通常是关于您访问工作表的次数。 每次你做这样的事情:你正在访问工作表的Cells(,).Value

良好实践的一个例子就是在同一时间内将所有的值都带进来,例如:

 Dim v as Variant v = Range("A1:A100").Value 

它只访问一次工作表,然后循环遍历结果variables数组,应用某种逻辑:

 For i = 1 to 100 v(i,1) = v(i,1) + 1 Next i 

然后一次返回工作表(再次访问工作表一次):

 Range("A1:A100") = v 

2

正如汤姆所说,不要使用Select 。 例如:

 Rows("4:4").Select With Selection.Font 

可能是

 With Rows("4:4").Font 

3

几个Application设置可能会加快你的速度

 'at beginning of code Application.ScreenUpdating = False Application.Calculation = xlCalculationManual 'at end of code Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic