2012-04-25 99 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