Excel VBA 删除没有特定值(文本)的行 - 抛出错误代码 13

问题描述 投票:0回答:1

Windows 10 Excel 2019

我有下面的 VB 代码,它抛出运行时代码 13 不匹配错误,但我不知道为什么。

我有一个 Excel 2019 工作表,其中 A - I 列中包含数据

此代码查看第一列,并在其中找到没有文本“S”或“M”或“S+M”的单元格 它应该删除整行。

这样只会留下 I 列具有“S”、“M”或“M+S”的行。

我也尝试过放置双“”之类的..

""S"", ""M"" or ""M+S""

但我仍然收到运行时代码 13 不匹配错误

我认为它应该有效,因为它只寻找特定的值,即文本或数字?

Sub DeleteRowsTEST()
' Defines variables
Dim Cell As Range, cRange As Range, LastRow As Long, x As Long


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


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


' For each cell in the check range, working from the bottom upwards
For x = cRange.Cells.Count To 1 Step -1
    With cRange.Cells(x)
        ' If the cell does not contain one of the listed values then...
        If .Value <> "M" And .Value <> "S" And .Value <> "M+S" Then
            ' Delete that row
            .EntireRow.Delete
        End If
    End With
' Check next cell, working upwards
Next x


End Sub
excel vba
1个回答
0
投票

选项 1

根据第一个代码,您可能会遇到的一个问题是,如果字符串与引号中显示的不完全一样,那么它不会删除该行。例如,如果字符串是“SM”而不是“MS”,它将保留。


子删除行测试()

'定义变量 Dim Cell As Range,LastRow As Long,x As Long,cellText As String

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

' For each cell in the check range, working from the bottom upwards
For x = LastRow To 1 Step -1

' goes row by row to get row and column "x, I" value
cellText = Worksheets("NAMEofYourSheet").Cells(x, 9).Value
   

    If cellText <> "M" Or cellText <> "S" Or cellText <> "MS" Then
        ' Delete that row
        Worksheets("NAMEofYourSheet").Cells(x, 9).Delete
    End If

'  Check next cell, working upwards
Next x

结束子


选项 2

编写代码的另一种方法是使用下面链接的 instr() 方法。如果您走这条路,您需要了解 instr 函数抛出的返回值。

https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/instr-function

子删除行测试()

' 定义变量 Dim Cell As Range,LastRow As Long,x As Long,cellText As String

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

' For each cell in the check range, working from the bottom upwards
For x = LastRow To 1 Step -1

' goes row by row to get row and column "x, I" value
cellText = Worksheets("NAMEofYourSheet").Cells(x, 9).Value
   

    If InStr(0, cellText, "M") > 0 Or InStr(0, cellText, "S") > 0 Then
        ' Delete that row
        Worksheets("NAMEofYourSheet").Cells(x, 9).Delete
    End If

'  Check next cell, working upwards
Next x

结束子

© www.soinside.com 2019 - 2024. All rights reserved.