【问题标题】:Delete rows based on REGEX pattern match excel VBA基于REGEX模式匹配excel VBA删除行
【发布时间】:2019-09-30 03:48:01
【问题描述】:

如果单元格值与正则表达式不匹配,我想在 excel 中使用宏来删除行。 更具体地说,如果单元格值不以数字开头,则删除整行

示例

宏之前

宏之后

所以我一直在尝试使用 .AutoFilter 将一些来自论坛的代码拼凑起来,但我不认为它需要一个正则表达式对象作为标准,只有字符串..

Sub test()
    Dim table As Range
    Dim ws As Worksheet
    Dim upperLeft As Range
    Dim digitOnly As Object

    Set digitOnly = CreateObject("vbscript.regexp")
    digitOnly.Pattern = "^[\d]"
    digitOnly.Ignorecase = True

    Set ws = ActiveSheet
    Set upperLeft = ws.Range("A2")
    Set table = upperLeft.CurrentRegion

    With table
    .AutoFilter Field:=1, Criteria1:=digitOnly
    .Offset(1, 0).EntireRow.Delete
    End With
    End Sub

有人可以提出一个替代方案,或者告诉我我做错了什么吗?谢谢你:)。

【问题讨论】:

  • 遍历行(通常从下往上)并删除 Not Cells(n, 1).Value Like "#*" 所在的行,您不需要 vbscript 正则表达式。查看此页面上“相关”下喜欢的帖子。
  • 谢谢。我会尝试这个

标签: excel vba autofilter


【解决方案1】:

类似这样的:

Sub test()
    Dim table As Range, c As Range
    Dim ws As Worksheet

    Set ws = ActiveSheet
    Set table = ws.Range("A2").CurrentRegion

    For i = table.columns(1).cells.count to 2 Step -1
        With table.columns(1).cells(i)
            If Not .Value like "#*" then .EntireRow.Delete
        End with  
    Next i

End Sub

【讨论】:

    【解决方案2】:

    根据@PaichengWu的推荐,我用了他的LIKE表情,看了一些其他相关的posts

    Sub DeleteRow()
        Dim i As Integer
        For i = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
            If Not Range("A" & i).Value Like "#*" Then
                Range("A" & i).EntireRow.Delete
            End If
        Next i
    End Sub
    

    快乐的小伙子 :) 谢谢。

    【讨论】:

      猜你喜欢
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      相关资源
      最近更新 更多