简体   繁体   中英

Delete entire row when a value exist in a second sheet

I have 2 sheets: sheet1 and sheet2. I have a value in cell A3 (sheet1) which is not constant. And many files in sheets2.

What I would like to do, is when the value in cell A3 (Sheet1) is the same as the value in the column A (Sheet2), it will delete the entire row where is find this value (Sheet2).

This is my attempt. It doesn't work: no rows are deleted.

If Worksheets("Sheet1").Range("A3").Text = Worksheets("Sheet2").Range("A:A").Text Then
    Dim f As String
    f = Worksheets("Sheet1").Range("A3")        
    Set c = Worksheets("Sheet2").Range("A:A").Find(f)
    Worksheets("Sheet2").Range(c.Address()).EntireRow.Delete
End If

My guess is that you're not finding anything with the .Find() . Since you're not checking it for is Nothing you don't know. Also, .Find() retains all the search parameters set from the last time you did a search - either via code or by hand in your spreadsheet. While only the What parameter is required, it's always worth setting the most critical parameters (noted below) for it, you may want to set them all to ensure you know exactly how you're searching.

Dim f As String

If Worksheets("Sheet1").Range("A3").Text = Worksheets("Sheet2").Range("A:A").Text Then
  f = Worksheets("Sheet1").Range("A3")
  Set c = Worksheets("Sheet2").Range("A:A").Find(What:=f, Match:=[Part|Whole], _
          LookIn:=[Formula|value])
  if not c is Nothing then
    Worksheets("Sheet2").Range(c.Address()).EntireRow.Delete
  else
    MsgBox("Nothing found")
  End If
End If

Go look at the MS docs to see what all the parameters and their enumerations are.

Sub Test()

Dim ws As Worksheet

For x = 1 To Rows.Count

If ThisWorkbook.Sheets("Sheet2").Cells(x, 1).Value = ThisWorkbook.Sheets("Sheet1").Cells(3, 1).Value Then ThisWorkbook.Sheets("Sheet2").Cells(x, 1).EntireRow.Delete

Next x

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM