我已经耗尽了我的知识/资源,试图弄明白这一点。我正在比较两列A& B.如果A中的值包含在B中,那么我的代码应仅从A中删除值。
A是完整的唯一列表,B是过滤的唯一列表。 B中的每个值都应该出现在A中.A中值的最终计数总是2390,而当前数据中B的最终计数总是2218。做数学,我期待A列中剩下178行。
当我运行以下代码时,每次都得到不同的最终计数。 253,242,249,246。我似乎无法理解问题来自于我的生活。我哪里出错了?
Sub RemoveDuplicateFromOneColumnComparingWithAnother()
Worksheets(2).Range("B:B").RemoveDuplicates Columns:=1
Application.ScreenUpdating = False
Dim rngCell As Range
Dim rngCheck As Range
For Each rngCell In Range("A1").CurrentRegion.Columns(2).Cells
If Not IsEmpty(rngCell) Then
Do
Set rngCheck = Nothing
On Error Resume Next
Set rngCheck = Worksheets(2).Range("A1").CurrentRegion.Columns(1).Find("*" & rngCell.Value & "*")
rngCheck.ClearContents
Err.Clear: On Error GoTo -1: On Error GoTo 0
Loop Until rngCheck Is Nothing
End If
Next rngCell
Set rngCell = Nothing
Set rngCheck = Nothing
End Sub
答案 0 :(得分:1)
此代码将列A中的每个值写入数组a()
,将列B中的每个值写入数组b()
。然后循环遍历a()
中的每个值。对于a()
中的每个值,它会遍历b()
中的每个值。如果找到该值,则会将flg
设置为TRUE
并且不会将其写入我们的数组c()
。如果flg
仍为FALSE
,则会将值写入数组c()
。然后我们返回并将c()
中的值写入C列。您可以对此进行调整,以将唯一身份(c()
)输出到您选择的任何位置。
<强>编辑:强>
Option Explicit
Sub test_array()
Dim a() As String, b() As String, c() As String
Dim flg As Boolean
Dim i As Long, j As Long, k As Long
Dim rng As Range
i = Range("a" & Rows.Count).End(xlUp).Row 'Edited to pull the row, not the cell
j = Range("b" & Rows.Count).End(xlUp).Row 'Edited to pull the row, not the cell
ReDim a(0 To i - 1)
ReDim b(0 To j - 1)
ReDim c(0 To i - 1)
For k = 0 To i - 1
a(k) = Cells(k + 1, "a")
Next k
For k = 0 To j - 1
b(k) = Cells(k + 1, "b")
Next k
k = 0
For i = 0 To UBound(a())
flg = False
For j = 0 To UBound(b())
If a(i) = b(j) Then
flg = True
Exit For
End If
Next j
If flg = False Then
k = k + 1
c(k - 1) = a(i)
End If
Next i
For k = LBound(c()) To UBound(c())
Cells(k + 1, "c") = c(k)
Next k
End Sub