简体   繁体   English

VBA-根据列值删除行

[英]VBA - delete rows based on a column value

I'm attempting to write a small piece of code for an ActiveX control button. 我试图为ActiveX控件按钮编写一小段代码。 I'm not the best with VBA and only do this in my free time so spare me some grace... I have a spreadsheet of "Master Inventory". 我在VBA上不是最好的,并且只能在空闲时间这样做,所以请您留心一点...我有一个“主库存”电子表格。 Columns "B" through "N" contain data about the inventory. 列“ B”到“ N”包含有关库存的数据。 Once the inventory is shipped, it's notated in column "N" with a "Y" (for Yes). 发货后,在“ N”列中用“ Y”表示(代表“是”)。

  1. I want my Activex Control button to ONLY delete rows (B3:N98) where column "N" = "Y". 我希望我的Activex控件按钮仅删除其中“ N” =“ Y”列的行(B3:N98)。
  2. I do not want formatting or formulas to be deleted - ONLY values. 我不希望删除格式或公式-仅值。
  3. I would like the data to be condensed and pushed to the top of the list after rows are deleted. 我希望在删除行后将数据压缩并推到列表的顶部。

I have been successful with #2, but not #1 or #3. 我在#2上取得了成功,但在#1或#3上却没有。 I'm deleting all rows but can't seem to get my "If" statement correct to only recognize those "Y" values. 我正在删除所有行,但似乎无法正确显示“ If”语句以仅识别那些“ Y”值。

Any help is greatly appreciated. 任何帮助是极大的赞赏。

Private Sub CommandButton1_Click()
    On Error Resume Next
    For I = 3 To 498
        If Range(I, "N").Text = "Y" Then
            Range("B3:N27").SpecialCells(xlCellTypeConstants).ClearContents
        End If
    Next I
End Sub

When deleting rows, you need to start at the bottom and work upward so that the remaining row numbers don't change. 删除行时,您需要从底部开始并向上移动,以使其余行号保持不变。 Column "N" is 14, so you can use logic like this. 列“ N”为14,因此您可以使用这样的逻辑。

Sub DeleteRows()
Dim I As Long
For I = 498 To 3 Step -1
If Cells(I, 14).Value = "Y" Then
Rows(I).EntireRow.Delete
End If
Next I
End Sub

A much faster way is to create a range object to hold all of the rows marked for deletion and then perform the delete all at once at the end. 一种更快的方法是创建一个范围对象,以保存标记为删除的所有行,然后在最后一次全部删除。 Deleting rows one-by-one inside of a loop can be painfully slow in Excel, especially as the number of rows grows in size. 在Excel中,在循环中一一删除行可能会非常缓慢,特别是随着行数的增加而增加时。

Try this: 尝试这个:

Public Sub DeleteRowsWithRange()

Dim rngLoop As Range
Dim rngMyRange As Range

    For Each rngLoop In Columns("N").Cells

    If rngLoop.Value = "" Then ' This is your exist clause. You can change this depending on your worksheet structure.
        Exit For  
    ElseIf rngLoop.Value = "N" Then
        If rngMyRange Is Nothing Then
            Set rngMyRange = rngLoop.EntireRow
        Else
            Set rngMyRange = Union(rngMyRange, rngLoop.EntireRow)
        End If
    End If

    Next rngLoop

    rngMyRange.Delete xlShiftUp

    Set rngLoop = Nothing
    Set rngMyRange = Nothing

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM