Delete entire row when a value exist in a second sheet

白昼怎懂夜的黑 提交于 2019-12-31 05:54:05

问题


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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/29206068/delete-entire-row-when-a-value-exist-in-a-second-sheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!