我如何使用VBA做一个VLookup来比较两个不同的表并删除单元格表匹配的行?

我有一个Excel工作簿3张:限制,残疾人和代理人。 每天在A行的代号,我会手动添加一个符号列表。 我需要使用VBA查看代码中列A中的内容,并在限制表和禁用表中使用这两个符号。 如果股票是在限制或禁用列表中,我需要VBA删除该行。 我手动input到代号的符号列表可能每天都有所不同,所以我也需要使范围dynamic化。 结果应该是代码条的b栏中既不在限制列表中也不在禁用列表中的符号列表。

这里是一个例子:

限制:AAA,BBB

禁用:CCC,DDD

代号(A栏):AAA,CCC,EEE,FFF,GGG

所需结果:

代号(b栏):EEE,FFF,GGG

这使用数组,将相当快。

Sub foo() Dim tickSht As Worksheet Dim restSht As Worksheet Dim disaSht As Worksheet Dim tickArr() As Variant Dim restArr() As Variant Dim disaArr() As Variant Dim outArr() As Variant Dim i&, k&, j&, r&, d& Dim dishr As Boolean Dim tichr As Boolean Set tickSht = ThisWorkbook.Worksheets("Tickers") 'ensure that this is the correct sheet name Set restSht = ThisWorkbook.Worksheets("Restricted") 'ensure that this is the correct sheet name Set disaSht = ThisWorkbook.Worksheets("Disabled") 'ensure that this is the correct sheet name 'load arrays 'if you have a title row then change the "A1" to "A2" or the first row. 'If your data is in a differect column then change the column. With disaSht disaArr = .Range("A1", .Cells(.Rows.Count, 1).End(xlUp)).Value End With With restSht restArr = .Range("A1", .Cells(.Rows.Count, 1).End(xlUp)).Value End With r = Application.Evaluate("SUM(countifs(" & tickSht.Range("A1", tickSht.Cells(tickSht.Rows.Count, 1).End(xlUp)).Address & _ "," & restSht.Range("A1", restSht.Cells(restSht.Rows.Count, 1).End(xlUp)).Address & "))") d = Application.Evaluate("SUM(countifs(" & tickSht.Range("A1", tickSht.Cells(tickSht.Rows.Count, 1).End(xlUp)).Address & _ "," & disaSht.Range("A1", disaSht.Cells(disaSht.Rows.Count, 1).End(xlUp)).Address & "))") With tickSht tickArr = .Range("A1", .Cells(.Rows.Count, 1).End(xlUp)).Value ReDim outArr(1 To UBound(tickArr, 1) - d - t, 1 To 1) k = 1 For i = LBound(tickArr, 1) To UBound(tickArr, 1) dishr = False tichr = False For j = LBound(disaArr, 1) To UBound(disaArr, 1) If disaArr(j, 1) = tickArr(i, 1) Then dishr = True Next j For j = LBound(restArr, 1) To UBound(restArr, 1) If restArr(j, 1) = tickArr(i, 1) Then tichr = True Next j If Not tichr And Not dishr Then outArr(k, 1) = tickArr(i, 1) k = k + 1 End If Next i .Range("B1").Resize(UBound(outArr, 1), 1).Value = outArr End With End Sub 

这假定数据在所有三张表的A列中,并且没有标题行。 如果不同,那么需要做一些调整。

这是dynamic的,因为它总是发现所有三张​​纸上的数据的范围将它们加载到数组中,并遍历这些数据。

数组的使用限制了vba在excel中访问表单的次数,因此对于较大的数据集来说,它会更快。