比较列表并修改MSGBOX
IM希望比较WB1列B中的所有条目(可以在最高300,000个)中与WB2中的主列表,Tab“ Guide”,A列A(大约500个条目)相比。
如果WB1的B列B中有新条目,则我有一个MSGBOX出现,列出了要添加到WB2中的主列表中的新类型。
如果没有发现
任何新类型的帮助,我还希望MSGBox出现“所有类型有效”,这是非常感谢的。
Sub Compare()
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim lr1 As Long
Dim lr2 As Long
Dim rng1 As Range
Dim rng2 As Range
Dim c As Range
Dim msg As String
msg = "New types: "
Set sh1 = Sheets(1)
Workbooks.Open Filename:="filepath\Types.xls"
Set sh2 = Worksheets("Guide")
lr1 = Application.WorksheetFunction.CountA(sh1.Columns(1))
lr2 = Application.WorksheetFunction.CountA(sh2.Columns(1))
Set rng1 = sh1.Range("B2:B" & lr1)
Set rng2 = sh2.Range("A2:A" & lr2)
For Each c In rng1
If Len(c.Value) > 0 And Application.CountIf(rng2, c.Value) = 0 Then
msg = msg & vbNewLine & c.Value
End If
Next
Workbooks("Types.xls").Close SaveChanges:=False
MsgBox msg
End Sub
Im looking to compare all entries in column B of WB1 (can vary in amount up to 300,000), versus a master listing in WB2,tab "Guide", column A (circa 500 entries).
If there are new entries in column B of WB1, i have a msgbox appear listing the new types to be added to the master listing in WB2.
I would also like a msgbox to appear saying "all types valid" if there are no new types found
Any help greatly appreciated.
Sub Compare()
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim lr1 As Long
Dim lr2 As Long
Dim rng1 As Range
Dim rng2 As Range
Dim c As Range
Dim msg As String
msg = "New types: "
Set sh1 = Sheets(1)
Workbooks.Open Filename:="filepath\Types.xls"
Set sh2 = Worksheets("Guide")
lr1 = Application.WorksheetFunction.CountA(sh1.Columns(1))
lr2 = Application.WorksheetFunction.CountA(sh2.Columns(1))
Set rng1 = sh1.Range("B2:B" & lr1)
Set rng2 = sh2.Range("A2:A" & lr2)
For Each c In rng1
If Len(c.Value) > 0 And Application.CountIf(rng2, c.Value) = 0 Then
msg = msg & vbNewLine & c.Value
End If
Next
Workbooks("Types.xls").Close SaveChanges:=False
MsgBox msg
End Sub
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将
k声明为整数
,但是excel的行比整数
可以处理。将所有行/列计数变量声明为long
。实际上,使用
整数
而不是长
在VBA中没有任何好处,因此我建议始终使用long
。只有一些非常罕见的情况确实需要整数
:为什么要使用integer代替长度?
Countif 语句是错误的,缺少标准:
应该看起来像
标准
需要用计数标准代替。You declare
k As Integer
but Excel has more rows thanInteger
can handle. Declare all row/column counting variables asLong
instead.Actually there is no benefit in using
Integer
instead ofLong
in VBA therefore I recommend always to useLong
. Only some very rare cases really needInteger
:Why Use Integer Instead of Long?
Also your
CountIf
statement is wrong and missing the criteria:Should look like
Where
CRITERIA
needs to be replaced by your count criteria.