2012-04-25 155 views
0

我在文檔中有2張(帶電話號碼)。如果number1存在於sheet1中,我想從sheet2中刪除該行。Visual Basic Excel - 宏刪除行

我快到了(這是我第一次使用VBA)。但任何人都可以幫我完成最後一部分。

Sub CleanList() 

    Dim stopList As Range, cell1 As Range 

    Set stopList = Sheet1.Range("A1:A10000") 

    For Each cell1 In stopList 
     Dim fullList As Range, cell2 As Range 
     Set fullList = Sheet2.Range("A2:A10000") 

     For Each cell2 In fullList 
      If NumberFix(cell1.Value) = NumberFix(cell2.Value) Then 
       cell2.EntireRow.Delete 
      End If 
     Next cell2 
    Next cell1 

End Sub 

Private Function NumberFix(ByVal nr As String) As String 

    If Not nr.StartsWith("46") Then 
     nr = "46" + nr 
    End If 

    NumberFix = nr 

End Function 
+2

您使用的是哪個版本的Excel?你能澄清一下「需要幫助最後一部分」嗎?您可能需要查看http://www.ozgrid.com/VBA/RemoveDuplicates.htm,這是從範圍中刪除重複項的許多解決方案之一。 – ExternalUse 2012-04-25 12:35:53

+0

+ 1 @ExternalUse:Yup高級過濾器是刪除重複的最快方法之一 – 2012-04-25 14:13:04

回答

3

第一件事就是您使用nr.StartsWith的方式更多的是VB.NET式的。您希望在VBA函數(可能不是VB腳本BTW)是

Dim firstTwoChar As String 
firstTwoChar = Mid(nr, 1, 2) 

If Not firstTwoChar = "46" Then 
    nr = "46" + nr 
End If 

NumberFix = nr 

但是,即使與我說你不應該使用一個for...each iterator如果您要刪除的行。問題是當你刪除第5行然後第6行變成第5行,你去的下一行是行「6」,但實際上是第7行在原始列表中,有效地跳過原始行6.

您需要向後移動。像

Sub CleanList() 

    Dim stopList As Range, cell1 As Range 

    Set stopList = Sheet1.Range("A1:A10000") 

    For Each cell1 In stopList 
     Dim fullList As Range, cell2 As Range 

     Dim firstRowSheet2 As Integer, lastRowSheet2 As Integer, r As Integer 
     Dim sheet1sNumber As String 
     sheet1sNumber = NumberFix(cell1.Value) 'you really only need to do this once 
               so you may as well bring it out of 
               the for loop and store the value and 
               not recalculate each time 
     Dim cell2 As Range 
     For r = firstRowSheet2 To lastRowSheet2 Step -1 
         '"Step -1" allows you to move backwards through the loop 
      With Sheet2 
       Set cell2 = .Cells(r, 1) 
       If sheet1sNumber = NumberFix(cell2.Value) Then 
         cell2.EntireRow.Delete 
        End If 
      End With 

     Next r 

    Next cell1 

End Sub 

但是當然@ExternalUse是正確的。有很多內置選項可用於從列表中刪除重複項。除非你想學習VBA,否則這是一個很好的練習。

+0

+ 1 :)反向循環的好處。 – 2012-04-25 14:11:44

+0

非常感謝布拉德。我爲for循環添加了開始和結束值。唯一缺少的東西。現在就像魅力一樣。 – mannge 2012-04-27 11:44:15

+0

很高興聽到它的工作! – Brad 2012-04-27 12:00:55