我正在尝试运行一个宏,它查看一个字符串并确定最后两个字符是否等于“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
请帮忙!谢谢。
答案 0 :(得分:4)
从.Value
移除Right(Cells(i, "E"), 2).Value
。这是抱怨,因为功能 .Value
Right
答案 1 :(得分:4)
虽然你已经有了答案,但我不建议循环来实现这个目标。如果您有大量行,循环将会很慢。这是一种相对非常快的替代方案。我还对代码进行了评论,以便您在理解它时不会遇到任何问题......
<强>逻辑强>:
<强>代码强>:
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
<强>截图强>:
答案 2 :(得分: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
答案 3 :(得分: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
答案 4 :(得分: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