【问题标题】:VBA Skip File if Partial String Not found in Worksheet?如果在工作表中找不到部分字符串,VBA 跳过文件?
【发布时间】:2021-10-08 00:02:37
【问题描述】:

在工作表中搜索部分字符串的最有效方法是什么?

我正在尝试通过活动工作表的 C 列末尾在 C4 中搜索“N”。如果数组中没有出现“N”,那么我想关闭文件。如果确实出现“N”,我想打印一条消息“找到强制数据”

我知道您可以使用 countif 函数,总结它出现的次数,然后使用 if/then 来确定操作 - 但我想有更好的方法。想法?

我下面的代码在工作表中搜索“N”,然后删除它不存在的行。 注意:我想在搜索中包含 N 之后的 3 个空格

Image here:

Sub InspectColumn()
'Define variables
Dim Cell As Range, cRange As Range, LastRow As Long, x As Long
Dim Res As Variant

' Define LastRow as the last row of data based on column C
LastRow = ActiveSheet.Cells(Rows.Count, "C").End(xlUp).Row

' Sets check range as C1 to the last row of C
Set cRange = Range("C1:C" & LastRow)

' For each cell in the check range, working from the bottom upwards
For x = cRange.Cells.Count To 1 Step -1
    ' find if 'N   ' found in any cell in the row
    Res = Evaluate("COUNTIF(" & x & ":" & x & ", ""*N   *"")")
    
    ' if 'N   ' not found delete row
    If Res = 0 Then
        ActiveSheet.Rows(x).Delete
    End If
    
Next x

结束子

【问题讨论】:

  • 使用过滤器并删除?

标签: excel vba string conditional-statements partial


【解决方案1】:

类似的东西。我已将其作为答案,但需要进行一些调整。

Columns("A:A").AutoFilter Field:=1, Criteria1:="<>*N*"
Columns("A:A").SpecialCells(XlCellType.xlCellTypeVisible).EntireRow.Delete
Columns("A:A").AutoFilter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    相关资源
    最近更新 更多