2017-07-07 75 views
-1

我有兩個工作表,它們被放到TabName1和TabName2中。我試圖從一列拿這個值與列中的所有值匹配它,如果沒有找到該值,那麼我刪除從Sheet2的VBA代碼太慢 - 匹配列的值

這是代碼行,

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左右。所以,任何想法或建議,以提高過程的速度。提前致謝。

+1

嘗試在你的子文件的循環之外添加'Application.ScreenUpdating = False'和'Application.ScreenUpdating = True'。 –

+0

是的,它已經存在於Sub內部。 – Sid29

+4

^並且不要使用select,只是'Sheets(TabName2).Rows(i).Delete' –

回答

1

就像這樣,請注意對象變量的使用,雖然這在性能上可能可以忽略不計,但根據DRY,這是一種最佳實踐:分配對象一次,然後僅使用對象而不是重複呼籲Sheets("some sheet name")

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 
+0

標記爲答案,因爲沒有更好的答案提供了這個問題。 – Sid29