【问题标题】:delete all rows if the cell value does not start with cioi, 600t and htk4 [closed]如果单元格值不以 cioi、600t 和 htk4 开头,则删除所有行 [关闭]
【发布时间】:2020-02-08 09:24:30
【问题描述】:

我必须删除除第 4 列中以 cioi、600t 和 htk4 开头的行之外的所有行。我的 excel 也有标题,不应删除。将来这个列表我可以添加到我的宏中吗

【问题讨论】:

  • 你有没有尝试过?如果是这样,请编辑您的问题以包含您的代码。
  • 我已经尝试过了,但它不适用于多种条件假设在下面的代码中我提到了两个人名,但是当我运行宏时它不会保留与 nitya 相关的数据
  • Sub KeepOnlyAtSymbolRows() Dim ws As Worksheet Dim rng As Range Dim lastRow As Long Set ws = ActiveWorkbook.Sheets("Sheet2") lastRow = ws.Range("B" & ws.Rows.Count ).End(xlUp).row Set rng = ws.Range("B1:B" & lastRow) '过滤并删除除标题行以外的所有内容 rng .AutoFilter Field:=1, Criteria1:=Array("*Nitya *", "*Solaman*") .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With ' 关闭过滤器 ws.AutoFilterMode = False End Sub

标签: excel vba excel-2010 excel-2007


【解决方案1】:

试试这个代码:

'find last populated row
xEndRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

'iterate all rows from bottom to top
For I = xEndRow To 2 Step -1
   'get value of cell at current row and 4th column
   currentCellValue = ActiveSheet.Cells(I, 4).Value
   'get first 4 characters
   startsWith = Left(currentCellValue, 4)

   'if row doesnt met criteria, delete it
   If startsWith <> "cioi" And startsWith <> "600t" And startsWith <> "htk4" Then
       Rows(I).Delete
   End If

Next

您可能希望使其更具动态性,因为由于缺乏相关细节,所有内容都是硬编码的。


无论如何,这是我之前测试数据的图像:

在运行宏之后:

【讨论】:

  • 嗨@mdelapena 非常感谢,你能提供完整的代码
  • 嗨@mdelapena 非常感谢,你能提供完整的代码
  • 这是完整的代码,只需将其添加到您的工作簿模块中,如果您需要帮助,请查看此link
  • 另外,标记为答案将不胜感激。
  • 非常感谢先生,但它仅适用于第三个值的前两个值,它正在删除所有行......假设我已经给出了六个值以及以上 3,但它保持 cioi,600t并删除所有剩余的 4
猜你喜欢
  • 2013-08-03
  • 1970-01-01
  • 2012-11-15
  • 2015-11-02
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
  • 2014-05-07
  • 2022-01-23
相关资源
最近更新 更多