删除不需要的数据行

时间:2016-06-29 16:29:17

标签: excel vba excel-vba

Dim mRange As Range

Columns("B:B").Select

i = 0
Set mRange = Range("B:B")
mRange.Find(What:="TRUE", After:=ActiveCell, LookIn:=xlValues, LookAt _
    :=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _
    False).Activate
Rows(ActiveCell.Row).Select
Selection.Delete Shift:=xlUp

For i = 0 To 1
Columns("B:B").Select
Set mRange = Range("B:B")
mRange.Find(What:="TRUE", After:=ActiveCell, LookIn:=xlValues, LookAt _
    :=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _
    False).Activate
Rows(ActiveCell.Row).Select
Selection.Delete Shift:=xlUp

Do While Not mRange Is Nothing
Set mRange = Range("B:B")
mRange.Select

mRange.Find(What:="TRUE", After:=ActiveCell, LookIn:=xlValues, LookAt _
    :=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _
    False).Activate
Rows(ActiveCell.Row).Select
Selection.Delete Shift:=xlUp

Loop

Next i

上面的代码正确地删除了单元格中包含单词" TRUE"在其中,但当它无法再找到" TRUE"时收到此错误。它不会跳出循环,但会挂起最后的mRange.Find方法。我做错了什么? THX。

"运行时错误91,对象变量或未设置块变量"

2 个答案:

答案 0 :(得分:3)

正如评论所示,摆脱.Select

此代码应该是所有需要的。

Do 

   Dim sAdd as String
   sAdd = vbNullString

   Dim rFound as Range
   Set rFound = Range("B:B").Find(What:="TRUE", After:=Cells(Rows.Count,Columns.Count), LookIn:=xlValues, LookAt _
    :=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _
    False)

   If Not rFound is Nothing Then
      sAdd = rFound.Address         
      rFound.EntireRow.Delete Shift:=xlUp
   End If

Loop Until sAdd = vbNullString

这也可以工作,如果行集不是非常大,可能会更快。

Dim lRow as Long
lRow = Range("B" & Rows.Count).End(xlUp).Row

With Range("B1:B" & lRow)
    .AutoFilter 1, TRUE
    .Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    .AutoFilter
End With

答案 1 :(得分:0)

Application.ScreenUpdating = False
Dim rFound As Range
Dim mRange As Range

Set mRange = Range("B:B")

Do

    Set rFound = mRange.Find(What:="TRUE", After:=ActiveCell, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
    If Not rFound Is Nothing Then rFound.EntireRow.Delete

Loop Until rFound Is Nothing

Application.ScreenUpdating = True