2012-12-20 28 views
0

我想刪除行只有當日期是過去的今天,但不是如果它是未來或空白。現在,如果沒有空白,我很難讓代碼不刪除行,因爲我想保留沒有日期的行。刪除行如果日期已經過去了,但不是如果單元格是空白VBA

Sub deleteSpudedWells() 
Dim lastRow As Integer 
Dim firstRow As Integer 
Dim ctr As Integer 

Dim currentCell As Range 
Dim valueOfDColumn 
Dim NoNSpudedWells As Boolean 



lastRow = 300 
firstRow = 10 

Application.ScreenUpdating = False 
With Sheets("NDIC Renewals") 
    For ctr = lastRow To firstRow Step -1 
     Set currentCell = .Cells(ctr, 4) 
     valueOfDColumn = currentCell.Value 
     NoNSpudedWells = valueOfDColumn >= Date 


     If Not NoNSpudedWells Then 
      Debug.Print "deleting row of cell " + currentCell.Address 
      currentCell.EntireRow.Delete 
     End If 
    Next 
End With 
Application.ScreenUpdating = True 
End Sub 

回答

1

添加其他條件,你如果:

If Not NoNSpudedWells AND valueOfDColumn <> 0 Then 

如果currentCell是空白的,它的價值將= 0

+0

如果單元格爲空,豈不是空「」? – bonCodigo

+1

@bonCodigo不,從技術上講它是空的。當作爲數字使用時,它的計算結果爲0.所以,在這方面,它將= 0.它也會=「」。在這方面你的回答不是比我的更正確或不正確。我只是簡單地指出一種方法,儘可能少地修改OP代碼,以獲得所描述的結果。 –

+0

我正在檢查'cell.value返回null',但正如你所說的那樣,根據它所評估的類型,值會得到掩碼;)謝謝+1 – bonCodigo

1

嘗試了這一點:

For ctr = lastRow To firstRow Step -1 
     Set currentCell = .Cells(ctr, 4) 
     valueOfDColumn = currentCell.Value    

     If NOT (valueOfDColumn >= Date or currentCell.Value = "") Then 
      Debug.Print "deleting row of cell " + currentCell.Address 
      currentCell.EntireRow.Delete 
     End If 
    Next 

BTW 最好宣佈你的valueOfDColumnDate,而不是把它留給是默認variant :)

+0

Upvoted這是因爲我不喜歡當OPs回答自己的問題,並引用其他答案作爲他們的參考。但後來我意識到這是錯誤的,所以我不得不爲你解決它。 ;-)刪除Not並且使用'valueOfDColumn 「」' –

+0

@DanielCook OP似乎已經這麼做了......「 ,'日期'和'<>「」' – bonCodigo

1

由於BonCodigo它給了我一個想法,我能adjuct代碼工作。需要閱讀這使代碼運行正常valueOfDColumn =「」

Sub deleteSpudedWells() 
    Dim lastRow As Integer 
    Dim firstRow As Integer 
    Dim ctr As Integer 

    Dim currentCell As Range 
    Dim valueOfDColumn 
    Dim NoNSpudedWells As Boolean 

    lastRow = 300 
    firstRow = 10 

    Application.ScreenUpdating = False 
    With Sheets("NDIC Renewals") 
     For ctr = lastRow To firstRow Step -1 
      Set currentCell = .Cells(ctr, 4) 
      valueOfDColumn = currentCell.Value 
      NoNSpudedWells = valueOfDColumn >= Date Or valueOfDColumn = "" 

      If Not NoNSpudedWells Then 
       Debug.Print "deleting row of cell " + currentCell.Address 
       currentCell.EntireRow.Delete 
      End If 
     Next 
    End With 
    Application.ScreenUpdating = True 
End Sub 
+1

然後你可以'回答'如答案;) – bonCodigo

相關問題