根据Workbook1中的单元格值删除Workbook2中的多行

时间:2016-04-19 00:30:59

标签: excel vba excel-vba

  1. 我需要VBA代码,根据Workbook1(A1)中单元格的值打开Workbook2。
  2. B:B列(工作簿1)中有值,如果这些值与A:A列(工作簿2)中可用的值相同,则删除(Workbook2)中包含相同值的整行。 / LI>

    有人可以帮我创建代码吗?

    我试过这个......

        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
    

2 个答案:

答案 0 :(得分:1)

假设如下:

1)您创建了两个名为WorkBook1和WorkBook2

的工作簿对象

2)您正在比较列" A"在两本书中都有一张名为" 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

这将只留下一个空白单元格而不删除该行,删除该行会更加棘手,因为for each循环将脱离sink并错过行。 如果您需要移除的行不仅仅是已清除,那么简单的解决方法是在列之后对列进行排序,并且空白将全部移动到底部。只需使用宏记录记录排序。

祝你好运

答案 1 :(得分:0)

非常感谢我对代码进行了一些修改,但它确实有效。

    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`

`