0

ドキュメントに2枚(電話番号付き)があります。番号がsheet1に存在する場合、シート2から行を削除します。

もうすぐです(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
4

1 に答える 1

3

まず最初に、nr.StartsWithVB.NET風の使用方法を使用します。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"ですが、実際には元のリストの行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を学習しようとしているのでない限り、これは良い演習です。

于 2012-04-25T12:51:08.890 に答える