关闭。这个问题需要更多 focused .它目前不接受答案。
想改进这个问题?更新问题,使其仅关注一个问题 editing this post .
5年前关闭。
Improve this question
我有一个包含 3 张工作表的 excel 工作簿:受限、禁用和自动收报机。每天在代码的 A 列中,我将手动添加符号列表。我需要使用 VBA 对股票代码中 A 列中的内容进行 vlookup,其中包含受限表和禁用表中的符号。如果代码在受限或禁用列表中,我需要 VBA 删除该行。我手动输入到代码中的符号列表可能每天都在变化,所以我还需要使范围动态。结果应该是代码表 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 列中,并且没有标题行。如果不同,则需要进行一些调整。
这是动态的,因为它总是在所有三个工作表上找到数据的范围,将它们加载到数组中并遍历它们。
数组的使用限制了 vba 在 excel 中访问工作表的次数,因此使用更大的数据集会更快。
关于vba - 如何使用 VBA 进行 VLookup 比较 2 个不同的表并删除单元格表匹配的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38794199/