[英]Remove row if cell value not in list
I have 2 sheets : in the first i have date and in sheet2 i have a list of names in column A . 我有两张纸:第一张纸上有日期,第二张纸上有A列的姓名。 I want to delete all the rows that don't have the names from sheet2 in the column O from the first sheet.
我想从第一张工作表中删除列O中没有工作表名称的所有行。 The code just deletes everything from the first sheet.
该代码仅删除第一张表中的所有内容。 Any help is welcomed.
欢迎任何帮助。
Sub Demo()
Dim Rng As Range, List As Object, Rw As Long
Dim x As Date
x = Now()
Set List = CreateObject("Scripting.Dictionary")
With Sheets("Sheet2")
For Each Rng In .Range("A1", .Range("A" & Rows.Count).End(xlUp))
If Not List.Exists(Rng.Value) Then
List.Add Rng.Value, Nothing
End If
Next
End With
With Sheets("query " & Format(x, "dd.mm.yyyy"))
For Rw = .Range("O" & Rows.Count).End(xlUp).Row To 1 Step -1
If Not List.Exists(.Cells(Rw, "O").Value) Then
.Rows(Rw).Delete
End If
Next
End With
Set List = Nothing
End Sub
I'm not sure if this does exactly what you wants, but it does something very similar. 我不确定这是否完全符合您的要求,但是它的功能非常相似。 To be clear:
要清楚:
Marks the cell adjacent to the list of names in Sheet1, if the name is found, then subsequently deletes the entire row if the the cell in said adjacent column is empty. 如果找到名称,则在Sheet1中标记与名称列表相邻的单元格,然后如果所述相邻列中的单元格为空,则随后删除整行。
Sub Macro()
Dim r As Long
Dim r2 As Long
Dim counter As Long
Dim counter2 As Long
Range("O1").Select
Selection.End(xlDown).Select
r = ActiveCell.Row
Sheets(ActiveSheet.Index + 1).Select
Range("A1").Select
Selection.End(xlDown).Select
r2 = ActiveCell.Row
Range("A1").Select
For counter = 1 To r2
needle = ActiveCell.Value
Sheets(ActiveSheet.Index - 1).Select
On Error GoTo NotFound
Range(Cells(1, 15), Cells(r, 15)).Find(needle).Select
Selection.Offset(0, 1).Value = "found"
NotFound:
Sheets(ActiveSheet.Index + 1).Select
Selection.Offset(1, 0).Select
Next
Sheets(ActiveSheet.Index - 1).Select
Range("P1").Select
For counter2 = 1 To r
If ActiveCell.Value = "" Then Selection.EntireRow.Delete
Selection.Offset(1, 0).Select
Next
Cleanup:
Range("P1:P10000").Value = ""
End Sub
It is however, rather ugly and inefficient code. 但是,它是丑陋且效率低下的代码。 Lmk if there's something that needs changing!
LMK,如果有需要更改的地方!
i would do it like this: 我会这样做:
Dim i as integer
dim x as integer
Dim rngSearch as Range
Dim strName as String
Dim ws1 as Worksheet
dim ws2 as Worksheet
Set ws1 = Thisworkbook.worksheets(1)
Set ws2 = Thisworkbook.worksheets(2)
x = ws1.cells(ws1.rows.count,1).end(xlup).row
for i = 2 to x
strName = ws1.cells(i, 1)
set rngSearch = ws2.columns(15).find(strName)
if rngSeach is nothing then
ws1.rows(i).entirerow.delete
i = i-1
end if
next i
It's not tested but it should work like this. 它未经测试,但应该可以这样工作。
Edit: I think you have to put the worksheets in right order. 编辑:我认为您必须按正确的顺序放置工作表。 I think i mixed them up here.
我想我把它们混在一起了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.