如果工作表B中满足条件,则从工作表A中删除行

时间:2014-07-22 09:08:56

标签: excel excel-vba vba

我想问这个问题,即我有两个具有相似数据的工作表。但是,在工作表B中,当我有一个条件时,请说一个列,供我输入"完成"。它将删除工作表A中满足此条件的相同数据。

我的宏:

Private Sub CommandButton1_Click()

Dim SO As String
Dim Balance As Integer
Dim Source As Worksheet, Target As Worksheet
Dim ItsAMatch As Boolean
Dim i As Integer

Set Source = ThisWorkbook.Worksheets("Customer Specific Stock")
Set Target = ThisWorkbook.Worksheets("Stock (Data)")
SO = Source.Range("K3")


Do Until IsEmpty(Target.Cells(2 + i, 5)) ' This will loop down through non empty cells from row 2 of column 4
    If Source.Cells(2 + i, 5) = SO Then
        ItsAMatch = True
        Target.Cells(2 + i, 1) = ""
        Target.Cells(2 + i, 2) = ""
        Target.Cells(2 + i, 3) = ""
        Target.Cells(2 + i, 4) = ""
        Target.Cells(2 + i, 5) = "" 
        Target.Cells(2 + i, 6) = ""
        Target.Cells(2 + i, 7) = ""
        Target.Cells(2 + i, 8) = "" ' This will overwrite your the value if PO is covered
        Exit Do
    End If
    i = i + 1
Loop

Set Source = Nothing
Set Target = Nothing



End Sub

根本不起作用。我哪里出错了?另一个问题是,当我在模块中放置一个宏时,如何将它与命令按钮一起使用?

1 个答案:

答案 0 :(得分:0)

看起来您的问题出在声明" Exit Do。"因为在满足匹配条件时退出循环,所以您的代码将仅删除第一个匹配项。如果你消除了它,它将通过所有非空单元格。我制作了一个简化版本,我认为你的数据可能是这样的:

enter image description here

enter image description here

以下是改编的代码:

Sub Stack()
Dim SO As String
Dim Balance As Integer
Dim Source As Worksheet, Target As Worksheet
Dim ItsAMatch As Boolean
Dim i As Integer
Set Source = ThisWorkbook.Worksheets("Customer Specific Stock")
Set Target = ThisWorkbook.Worksheets("Stock (Data)")
SO = "Done"
i = 0
Do Until IsEmpty(Target.Cells(2 + i, 1)) ' This will loop down through non empty cells from row 2 of column 4
On Error Resume Next
If Application.WorksheetFunction.VLookup(Target.Cells(2 + i, 1), Source.Range("A1:B100"), 2, False) = SO Then
    ItsAMatch = True
    Target.Cells(2 + i, 1) = ""
    Target.Cells(2 + i, 2) = ""
    Target.Cells(2 + i, 3) = ""
    Target.Cells(2 + i, 4) = ""
    Target.Cells(2 + i, 5) = ""
    Target.Cells(2 + i, 6) = ""
    Target.Cells(2 + i, 7) = ""
    Target.Cells(2 + i, 8) = ""
End If
On Error GoTo 0
i = i + 1
Loop
Set Source = Nothing
Set Target = Nothing
End Sub

将这些已经喂食的动物排成一行,导致:

enter image description here