2016-10-24 22 views
0

在VBA試圖刪除所有行,直到電池(A,1)具有一定的價值

有問題試圖刪除所有行,直到值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。

+1

您可能想要包括'Range(「A」&i).Value = vbNullString'。否則,上面的代碼可能會無限期運行(如果從未找到'** GRAD'),甚至可能會導致計算機崩潰。這就是爲什麼我(個人)試圖完全避免使用「Do Loop」並僅使用「For ... Next」(具有明確的結束行,即使它必須是最後一行= 1,048,576)。 – Ralph

+0

總是使用'選項顯式',你的錯別字將很容易識別! –

回答

0

L.Dutch已經給你回答你的問題

這裏是一個替代性和更快的方法

以刪除列中的所有行,直到值 1 =「** GRAD *」

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 
+0

這是更快我試圖修改你的代碼刪除空行後的所有行,但我認爲我的方法很髒, –

+0

你可能想發佈一個新問題,你的新問題「如何刪除一行空白後的所有行」,添加更多的細節和主要_your_代碼嘗試 – user3598756

+0

謝謝你的幫助,我很漂亮新的這個網站。 –

1

錯字?我讀If .Rage("A" & i).Value <> "**GRAD" Then而應該是If .Range("A" & i).Value <> "**GRAD" Then

+1

非常感謝你,愚蠢的錯誤! –

+0

可能你是新來的,而不是「謝謝」,它被認爲通過標記它的有用或接受來認識答案 –

相關問題