Excel VBA代码太慢-与列的值匹配

Excel VBA代码太慢-与列的值匹配,excel,vba,Excel,Vba,我有两张表,它们分别放在TabName1和TabName2中。我试图从一列中获取值,并将其与该列中的所有值进行匹配,如果未找到该值,则我将从sheet2中删除该行 这是代码 For i = lastrow To 2 Step -1 CombinedKeyVal = Sheets(TabName2).Range(CombinedKeyColLet & i).Value Present = Application.Match(CombinedKeyVal, Sheets(Ta

我有两张表,它们分别放在TabName1和TabName2中。我试图从一列中获取值,并将其与该列中的所有值进行匹配,如果未找到该值,则我将从sheet2中删除该行

这是代码

For i = lastrow To 2 Step -1
    CombinedKeyVal = Sheets(TabName2).Range(CombinedKeyColLet & i).Value
    Present = Application.Match(CombinedKeyVal, Sheets(TabName1).Columns(CombinedKeyCol), 0)
    If IsError(Present) Then
        Sheets(TabName2).Rows(i & ":" & i).Select
        Selection.Delete
    End If

Next
是的,最后一行定义为

lastrow = Sheets(TabName1).Cells(Rows.Count, BuColm).End(xlUp).Row

它起作用了。但是它太慢了。我最后一排大约5000人。因此,任何提高流程速度的想法或建议。提前感谢。

类似的内容,请注意
工作表
对象变量的使用,虽然这在性能上可能可以忽略不计,但根据DRY的说法,这是一种最佳做法:分配对象一次,然后只使用对象,而不是重复调用
工作表(“某些工作表名称”)


尝试将
Application.screenUpdatement=False
Application.screenUpdate=True
添加到sub.^的循环之外,并且不使用选择,只使用
工作表(选项卡名称2)。行(i)。删除
不使用
select
,这会降低宏速度。是否禁用了计算和屏幕更新?在运行时,这些都是麻烦。每次删除一行时,工作表都需要重新计算。禁用这两个选项,并在过程结束时重新启用。将其标记为“答案”,因为没有为该问题提供更好的答案。
Dim sh2 as Worksheet, sh1 As Worksheet
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Set sh2 = Sheets(TabName2)
Set sh1 = Sheets(TabName1)

''' more code goes here when you calculate lastrow, etc.

For i = lastrow To 2 Step -1
    CombinedKeyVal = sh2.Range(CombinedKeyColLet & i).Value
    Present = Application.Match(CombinedKeyVal, sh1.Columns(CombinedKeyCol), 0)
    If IsError(Present) Then
        sh2.Rows(i).EntireRow.Delete 
    End If
Next
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True