尝试删除所有行,直到Cell(A,1)具有特定值

时间:2016-10-24 09:47:05

标签: excel vba

在VBA中遇到问题

尝试删除所有行,直到第1行中的值=“** GRAD *”

我得到运行时错误438

以下代码

Public Sub Delete()

Dim i As Long

i = 1 'Start from row 1

Application.ScreenUpdating = False

With ThisWorkbook.Worksheets("Sheet1")

    Do Until .Range("A" & i).Value = "**GRAD"
        If .Rage("A" & i).Value <> "**GRAD" Then
            .Rows(i).EntireRow.Delete
        Else: i = i + 1 'Only increment if the row hasn't been deleted to        prevent skipping rows
        End If
    Loop

End With

Application.ScreenUpdating = True

End Sub

一些帮助将不胜感激,是VBA的新手。

2 个答案:

答案 0 :(得分:1)

错字?我看了If .Rage("A" & i).Value <> "**GRAD" Then,而它应该是If .Range("A" & i).Value <> "**GRAD" Then

答案 1 :(得分:1)

L.Dutch已经给你答案了你的问题

这是另一种更快捷的方法

  

删除所有行,直到列中的值 1 =&#34; ** GRAD *&#34;

Option Explicit

Public Sub Delete()
    Dim lastRowToDelete As Long
    Dim f As Range

    With ThisWorkbook.Worksheets("Sheet0001") '<-- reference your worksheet
        With Range("A1", .Cells(.Rows.Count, 1).End(xlUp)) '<-- reference its columns "A" cells from row 1 sown to last not empty one
            Set f = .Find(what:="**GRAD", LookIn:=xlValues, lookat:=xlWhole, after:=.Range("A" & .Rows.Count)) '<-- look for the first cell whose value is "**GRAD"
            If f Is Nothing Then '<-- if not found then...
                lastRowToDelete = .Rows(.Rows.Count).Row '<-- the last row to delete is the last row of the range
            Else '<-- otherwise...
                lastRowToDelete = f.Row - 1 '<-- the last row to delete is the one preceeding the one with the found cell
            End If
        End With
        If lastRowToDelete > 0 Then .Range("A1:A" & lastRowToDelete).EntireRow.Delete 'delete all rows in a single shot
    End With
End Sub