2012-04-25 21 views
0

ドキュメントに2枚の(電話番号付き)があります。シート1に番号がある場合は、シート2から行を削除します。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のバージョンはどれですか?そして、あなたは「最後の部分で助けが必要です」ということについて少し明確にすることができますか?範囲から重複を削除する多くのソリューションの1つであるhttp://www.ozgrid.com/VBA/RemoveDuplicates.htmをご覧になることをお勧めします。 – ExternalUse

+0

+1 @ExternalUse:Yupアドバンストフィルタは、重複を削除する最も速い方法の1つです。 –

答えて

3

最初のことは、nr.StartsWithがVB.NET-esqueであることです。あなたは、VBAで探している機能(おそらくVBスクリプトところで)は

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

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

NumberFix = nr 

あるしかし、たとえそれで私はあなたが行を削除している場合は、for...eachイテレータを使用すべきではないと思います。問題は、行5を削除すると行6が行5になり、次の行に行6が表示されますが、元の行6では実際に行7になります。

後方に移動する。何かのように

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:逆ループの良い点。 –

+0

ありがとう。ブラッド。 forループの開始値と終了値を追加しました。紛失したものだけ。今の魅力のように動作します。 – mannge

+0

それはうまくいっていることを聞いてよかった! – Brad

関連する問題