简体   繁体   中英

Delete multi Rows in Workbook2 depending on cell values in Workbook1

  1. I need VBA code that will open Workbook2 depending on value of a cell in Workbook1 (A1).
  2. In B:B column (Workbook1) there are values, if these values are the same as those available in A:A column (Workbook2) delete entire row that contains the same values in (Workbook2).

Can anyone help me to create the code?

i tried this one .....

    Private Sub CommandButton1_Click()
Dim WB1, WB2 As Workbook
Dim WS1, WS2 As Worksheet
Set WB1 = ThisWorkbook
CSN = Cells(1, 1)
Set WB2 = Workbooks.Open("C:\Users\Basel\Desktop\" & CSN & "")
Set WS1 = WB1.Worksheets("sheet1")
Set WS2 = WB2.Worksheets("Sheet1")

LastRow1 = WB1.WS1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
LastRow2 = WB2.WS2.Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To 20
If WB1.WS1.Cells(i, 2).Value = WB2.WS2.Cells(i, 1).Value Then
WB2.WS2.Cells(i, 1).EntireRow.Delete

End If

Next i

End Sub

Assuming the following:

1) you have created two workbook objects called WorkBook1 and WorkBook2

2) you are comparing column "A" in both books with the sheet called "sheet1"

Dim WB1sheet As Worksheet
Dim WB2sheet As Worksheet
Dim cell As Range
Dim cell2 As Range

Set WB1sheet = WorkBook1.Sheets("sheet1")
Set wb2sheet = Workbook2.Sheets("sheet1")

'Loop through colum A
For Each cell In WB1sheet.Range("a1", "a1000000")
   ' for each loop through the other sheet
   If cell = "" Then
      Exit For
   End If
   For Each cell2 In wb2sheet.Range("a1", "a1000000")
      If cell = cell2 Then
         cell2.ClearContents
         Exit For
      End If
   Next cell2
Next cell

End Sub

This will just leave a blank cell not delete the row, it is more tricky to delete the row because the for each loop will get out of sink and miss rows. If you need the row removed not just cleared then the easy fix is to do a sort on the column afterwards and the blanks will all move to the bottom. Just record the sort using macro record.

Good luck

thanks really i made some modification on the code but it works.

    Private Sub CommandButton1_Click()
Dim WB1, WB2 As Workbook
Dim WS1, WS2 As Worksheet
Dim CELL1 As Range
Dim CELL2 As Range

CSN = Cells(1, 1)
Set WB1 = ThisWorkbook
Set WB2 = Workbooks.Open("C:\Users\Basel\Desktop\" & CSN & "")
Set WS1 = WB1.Worksheets("sheet1")
Set WS2 = WB2.Worksheets("Sheet1")

For Each CELL1 In WS1.Range("B1", "B10")
If CELL1 = "" Then
Exit For
End If
For Each CELL2 In WS2.Range("A1", "A10")
If CELL1 = CELL2 Then
CELL2.EntireRow.Delete
Exit For
End If
Next CELL2
Next CELL1

WB2.Save
WB2.Close
Range("B:B").ClearContents

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