我的文档中有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
答案 0 :(得分: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,否则这是一个很好的练习。