简体   繁体   English

VBA:根据列中第一次出现的值删除 excel 行

[英]VBA: Deleting an excel row based on first occurrence of a value in a column

What is the best way using VBA to find the first occurrence of a specific value in column A and delete that entire row?使用 VBA 在 A 列中查找特定值的第一次出现并删除整行的最佳方法是什么? Example:例子:

  • A一个
  • A一个
  • B
  • B
  • B
  • C C
  • C C
  • C C
  • C C

I need to find each of the bold letters and delete all the data in their row.我需要找到每个粗体字母并删除其行中的所有数据。 This column will always have repeats as the report that exports this data sets the first row of each group (A,B, or C) as the total row.此列将始终重复,因为导出此数据的报告将每个组(A、B 或 C)的第一行设置为总行。

With VBA, you can go down the column and search for values that don't match the previous row.使用 VBA,您可以将 go 向下列并搜索与前一行不匹配的值。

Sub DropTotals()
   Set ws = Sheets("Sheet1")  ' sheet with data
   col = 1  ' data column to check
   rw = 2  ' data start row
   For ctr = 1 To 9999  ' prevent endless loop
      If ws.Cells(rw, col) = "" Then: Exit For  ' end of data
      If ws.Cells(rw, col).Value <> ws.Cells(rw - 1, col).Value Then ' if does not match previous row
          Rows(rw).EntireRow.Delete  ' delete row
      End If
      rw = rw + 1  ' next row
   Next
End Sub

Before: After:之前: 之后:

Excel之前之后

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

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