VBA Excel删除具有特定值的行

时间:2017-08-16 20:05:16

标签: excel vba excel-vba

我需要删除带有订单号的表中的特定行。当我将此代码放入Excel时,它会删除整个表。我想要的是只删除特定的行。 tbxOrder是一个文本框。我希望当文本框等于x命令编号时,代码将在“分页”表(第20列)中选择具有相同编号的所有行,然后删除它们。谢谢:))

Public Sub DeleteOrderRows()

Dim strNoOrder As String
Dim strNoFunction As String
Dim noCommande As Integer

Dim tblPagination As ListObject
Set tblPagination = Worksheets("Pagination").ListObjects.Item("tblPagination")

For Each srcrow In tblPagination.ListRows

strNoOrder = srcrow.Range.Cells(1, 20)
noOrder = tbxOrder.Value

If strNoOrder = noOrder Then

EntireRow.Delete

End If

Next

End Sub

2 个答案:

答案 0 :(得分:1)

不使用ListRows尝试;请改用DataBodyRange。从底部到顶部工作,或者您在删除时可能会跳过行。

Option Explicit

Public Sub DeleteOrderRows()

    Dim strNoOrder As String
    Dim strNoFunction As String, noOrder As String
    Dim noCommande As Integer
    Dim i As Long, tbxOrder As Range
    Dim tblPagination As ListObject

    Set tblPagination = Worksheets("Pagination").ListObjects.Item("tblPagination")

    'here I had to set tbvOrder and assign noOrder
    Set tbxOrder = Worksheets("Pagination").Cells(1, "A")
    noOrder = tbxOrder.Value

    With tblPagination.DataBodyRange.Columns(20).Cells
        For i = .Count To 1 Step -1
            Debug.Print .Cells(i).Address(0, 0)
            strNoOrder = .Cells(i).Value2

            If strNoOrder = noOrder Then
                .Cells(i).EntireRow.Delete
            End If

        Next i
    End With

End Sub

答案 1 :(得分:0)

另一种选择:

Public Sub DeleteOrderRows()
Dim rngToDelete As Range
Set rngToDelete = Nothing

Dim tblPagination As ListObject
Set tblPagination = Worksheets("Pagination").ListObjects.Item("tblPagination")

Dim strNopage As String
Dim strNoOrder As String

For Each currentRow In tblPagination.ListRows
    strNoOrder = currentRow.Range.Cells(1, 5).Value
    strNopage = tbxPage.Value
    If strNoCommande = strNopage Then
        If rngToDelete Is Nothing Then
            Set rngToDelete = currentRow.Range
        Else
            Set rngToDelete = Union(rngToDelete, currentRow.Range)
        End If
    End If
Next

If Not rngToDelete Is Nothing Then
    rngToDelete.Delete Shift:=xlUp
End If

End Sub