3

我正在尝试运行一个宏,它查看一个字符串并确定最后两个字符是否等于“XX”,然后删除整行。

我收到一个对象错误哦,下面突出显示。

Sub Oval2_Click()


Last = Cells(Rows.Count, "E").End(xlUp).Row

For i = Last To 1 Step -1

`If (Right(Cells(i, "E"), 2).Value) = "TZ" Then`

    Cells(i, "E").EntireRow.Delete

End If
Next i

End Sub

请帮忙!谢谢你。

4

5 回答 5

5

.Value从中删除Right(Cells(i, "E"), 2).Value。它在抱怨,因为函数.Value上不存在 Right

于 2013-01-09T21:18:31.217 回答
4

虽然你已经有了答案,但我不建议循环来实现这一点。如果您有大量行,循环会很慢。这是一个相对非常快的替代方案。我还对代码进行了注释,以便您理解它不会有问题......

逻辑

  1. 使用自动过滤器过滤以“XX”结尾的数据
  2. 删除过滤数据

代码

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long

    '~~> Change this to the respective sheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        '~~> Remove any filters
        .AutoFilterMode = False

        '~~> Get last row of Col A
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Use autofilter to identify the cells which end in "XX"
        With .Range("A1:A" & lRow)
            .AutoFilter Field:=1, Criteria1:="=*XX"
            '~~> Offset to exclude the header and delete them
            .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        End With

        '~~> Remove any filters
        .AutoFilterMode = False
    End With
End Sub

截图

在此处输入图像描述

于 2013-01-10T02:45:45.537 回答
2

这个

If (Right(Cells(i, "E"), 2).Value) = "TZ" Then

应该是

If Right(Cells(i, "E").Value, 2) = "TZ" Then

这也应该有效:

If Right(Cells(i, "E"), 2) = "TZ" Then
于 2013-01-09T21:12:48.493 回答
0

正如评论中提到的,我建议你把循环转过来(在相反的方向):

For counter = To Rng.Rows.Count To 1 Step -1
  If (Right(Rng.Cells(counter),2)) = "XX" Then
      Rng.Cells(counter).EntireRow.Delete
  End If
Next counter
于 2021-08-10T07:27:51.067 回答
0

我测试过。这行得通,而且是最快的,因为我也用它Range来加速代码。

Sub Oval2_Click()

    Dim Rng As Range 
    Dim i As Integer, counter As Integer
    'Please Set Your Range
    Set Rng = Range("E2:E300000")
    i = 1
    For counter =1 To Rng.Rows.Count
    
    If (Right(Rng.Cells(i),2)) = "XX" Then
        Rng.Cells(i).EntireRow.Delete
    Else 
       i = i + 1
    End If

    Next 

End Sub
于 2021-08-09T09:33:32.920 回答