2016-09-26 11 views
0

在我的專欄A中,我有格式化日期和常規格式組成的單元格。我想刪除不是日期的行,並且我已經創建了這些代碼,但是我必須多次運行它才能刪除所有不是日期的行。刪除未格式化爲日期的行

My column is like the one showed in the picture

代碼:

Sub del_row_not_date() 

Dim rng_A_last As Long 
Dim i As Integer 

rng_A_last = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row 
Debug.Print rng_A_last 

For i = 1 To rng_A_last Step 1 
    If IsDate(Sheet1.Cells(i, 1)) = False Then 
     Sheet1.Cells(i, 1).EntireRow.Delete 
    End If 
Next 
End Sub 

提前感謝!

回答

0

由於行將

基於此LINK我發現這個:

關於根據條件刪除行的提示如果你從頂部開始往下看,每次刪除一行時,你的計數器將有效地移動到你刪除的行下面兩行的單元格,因爲立即行在刪除的行下移動(即它根本沒有經過測試)。

這工作:)

Sub del_row_not_date() 

Dim rng_A_last As Long 
Dim i As Integer 

rng_A_last = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row 
Debug.Print rng_A_last 

For i = rng_A_last To 1 Step -1 
    'Debug.Print Cells(i, 1).Value 
    If IsDate(Sheet1.Cells(i, 1)) = False Then 
     Sheet1.Cells(i, 1).EntireRow.Delete 
    End If 
Next 
End Sub 
+0

這正是我在答覆代碼#2中指出的。但如果您的日期是「A」列中的唯一數字,那麼我的答案代碼#1會好得多(越來越快) – user3598756

0

你可以嘗試

Sub del_row_not_date() 
    With Sheet1 
     .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)).SpecialCells(xlCellTypeConstants, xlTextValues).EntireRow.Delete 
    End With 
End Sub 

什麼上面刪除所有列「A」不數字的單元格整行

,如果你有細胞與不是日期,然後用數字:

Option Explicit 

Sub del_row_not_date() 
    Dim i As Integer 

    With Sheet1 
     For i = .Cells(.Rows.Count, "A").End(xlUp).Row To 1 Step -1 '<--| loop backwards not to loose next row index after deleting the current one 
      If Not IsDate(.Cells(i, 1)) Then .Cells(i, 1).EntireRow.Delete 
     Next i 
    End With 
End Sub 
+0

謝謝,我會稍後再試和評論! – Grohl

+0

不客氣。等待您的意見,可能會進一步加強答案。而代碼#2實際上解決了您的問題,請將答案標記爲已接受。謝謝 – user3598756