如果单元格以某个单词结尾,如何删除整行? VBA

时间:2016-11-17 21:29:31

标签: excel vba excel-vba

我有一个超过10,000行的excel文件。我想运行一个VBA脚本,删除单词B中列reduce 结束的所有行。例如,如果我的列如下所示:

CostReduce
PriceReduce
ReducePrice
MaterialReduce
InfrastructureReduce
ReduceProfits
ReduceOverhead

我希望脚本能够运行并删除包含以Reduce结尾的单词的每一行。所以输出将是:

ReducePrice
ReduceProfits
ReduceOverhead

我现在拥有的脚本会删除包含单词reduce的所有行,而我不知道如何改变它以便它能够实现我想要的效果。

Sub DeleteReduce()

Dim ContainWord As String

Dim i As Integer
i = 2

ContainWord = "reduce"

Do While Range("B" & i) <> ""
    If Not Range("B" & i).Find(ContainWord) Is Nothing Then
        Range("B" & i).EntireRow.Delete
    Else
        i = i + 1
    End If
Loop
Range("B2").Select
End Sub

4 个答案:

答案 0 :(得分:1)

使用Right功能,对VB进行微小更改:

Sub DeleteReduce()

Dim ContainWord As String

Dim i As Integer
i = 2

ContainWord = UCase("reduce")

Do While Range("B" & i) <> ""
    If UCASE(right(Range("B" & i).value,len(ContainWord))) = ContainWord Then
        Range("B" & i).EntireRow.Delete
    Else
        i = i + 1
    End If
Loop
Range("B2").Select
End Sub

已更新以删除区分大小写

答案 1 :(得分:1)

你真的需要一个剧本吗?引入另一个简单= IF的列是不够的(RIGHT(B1,6)=&#34; reduce&#34;,&#34; yes&#34;,&#34; no&#34;)并应用过滤,然后删除行&#34;是&#34;值?

答案 2 :(得分:0)

检查单元格中的最后6个字符,看它们是否与Reduce相匹配。

Right(Range("B" & i ),6) = "Reduce"

Sub DeleteReduce()
Dim ContainWord As String
Dim i As Integer

  ContainWord = "Reduce"

  Do While Range("B" & i) <> ""
    If Right(Range("B" & i ),6) = ContainWord Then
      Range("B" & i).EntireRow.Delete
    Else
      i = i + 1
    End If
  Loop
  Range("B2").Select
End Sub

答案 3 :(得分:0)

此解决方案使用Autofilter设置要删除Range的{​​{1}},然后提供两种删除行的方法:

  1. 一次删除整个范围:但这可能会很慢,具体取决于区域数量,文件大小等。
  2. 按升序排列的区域(从下到上)删除结果范围。
  3. 以下代码中的两种方法都是“有效”,您需要注释未选择的方法。

    Rows