0

我的文档中有 2 张纸(带有电话号码)。如果数字存在于工作表 1 中,我想从工作表 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.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但即便如此,我会说如果您要删除行,您不应该使用迭代器。问题是当您删除第 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 回答