gpt4 book ai didi

excel - 比较 Excel 中的两个范围

转载 作者:行者123 更新时间:2023-12-02 15:29:31 30 4
gpt4 key购买 nike

我正在尝试比较两个范围的数据。 “A”包含 1,2,3,4,“B”包含 1,2,5。我想找到那些在“B”中但不在“A”中的内容,即 5。下面是我的代码,但我似乎无法得到我想要的。有人可以建议一下吗?

Dim a As Range, b As Range, i As Integer, x As Integer
Set a = Range("A1:A4")
Set b = Range("B1:B3")

For i = 1 To b.Count
For x = 1 To a.Count

If b(i, 1) = a(x, 1) Then

Else
MsgBox (b(i, 1))
Exit For
End If
Next x
Next i

最佳答案

这是一个非常小的范围,但我仍然建议使用数组来存储范围值,然后使用数组进行比较。请参阅此示例。

Sub Sample()
Dim Ar1, Ar2
Dim i As Long, j As Long
Dim Found As Boolean

Ar1 = Range("A1:A4"): Ar2 = Range("B1:B3")

For i = LBound(Ar2) To UBound(Ar2)
Found = False
For j = LBound(Ar1) To UBound(Ar1)
If Ar1(j, 1) = Ar2(i, 1) Then
Found = True
Exit For
End If
Next j

If Found = False Then Debug.Print Ar2(i, 1) & " Is unique"
Next i
End Sub

enter image description here

编辑

另一种方式(不过我仍然更喜欢上面的方式)

Sub Sample()
Dim rngA As Range, rngB As Range
Dim aCell As Range, bCell As Range
Dim Found As Boolean

Set rngA = Range("A1:A4"): Set rngB = Range("B1:B3")

For Each aCell In rngB
Found = False
For Each bCell In rngA
If bCell.Value = aCell.Value Then
Found = True
Exit For
End If
Next

If Found = False Then Debug.Print aCell.Value & " Is unique"
Next
End Sub

关于excel - 比较 Excel 中的两个范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16226122/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com