2016-02-16 53 views
0

我正在拼湊代碼以使我的宏正常工作。這種方法在過去很好,但我似乎無法正確地調整任何代碼。VBA中的條件刪除

我發現下面的

Sub way() 

Dim Cell As Range 
For Each Cell In Range("A1").CurrentRegion 
    If Len(Cell) < 2 Then Cell.EntireRow.Delete 
Next Cell 

End Sub 

我能適應如果len(小區)的標準來我的胃口。例如= 10

我不知道如何調整代碼以使其搜索列A中的所有單元格並刪除相應的行。上面的代碼只適用於A1。

理想情況下,我想刪除列A中具有10個字符長度的單元格的所有行。或者,也可以使用完全不同的代碼集,刪除不包含列A中長度爲10個字符的單元格的所有其他行。

回答

3

當刪除行最好是循環向後:

Sub way() 
Dim ws As Worksheet 
Dim i As Long 
Dim lastrow As Long 


Set ws = ActiveSheet 
lastrow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row 
For i = lastrow To 1 Step -1 
    If Len(ws.Cells(i, 1)) < 2 Then ws.Rows(i).Delete 
Next i 

End Sub 
-2

我沒有檢查語法,但這樣的事情應該工作:

dim idx as integer 
idx = 1 
while Range("A" + cstr(idx)).value <> "" 
    'insert your delete logic here... 
idx = idx + 1 
wend 
3

從本質上講,你的循環正在經歷Range.CurrentRegion property中的每個單元都從A1輻射出去。您的敘述表示您只想檢查A列,但刪除Range.EntireRow property

對於Scott Craner提出的下一步回退步驟可能是您最好的選擇,但如果您對For ...每個In循環更舒適,那麼您可以進行調整。

Sub way() 
    Dim cl As Range, dels As Range 

    With Worksheets("Sheet1") 
     For Each cl In .Range("A1").CurrentRegion.Columns(1).Cells 
      If Len(cl.Value2) = 10 Then 
       If Not dels Is Nothing Then 
        Set dels = Union(dels, cl) 
       Else 
        Set dels = cl 
       End If 
      End If 
     Next cl 
    End With 

    If Not dels Is Nothing Then _ 
     dels.EntireRow.Delete 

End Sub 

刪除不具有在列A中的值,該值是10個字符,符號或數字長將是If Len(cl.Value2) <> 10 Then行中的邏輯。