Add missing dates VBA

2020-04-16 04:23发布

I have to insert missing dates to a row without deleting the duplicated dates (for a billing program). Example data:

DATE
01/02/2016    
02/02/2016    
03/02/2016    
03/02/2016    
03/02/2016    
06/02/2016    
07/02/2016    
08/02/2016

My code is infinitely looping and deleting the duplicate dates. Why does this happen?

Sub InsertMissingDates()

Dim i As Long
Dim RowCount As Long

i = 4

Do
    If Cells(i, 1) + 1 <> Cells(i + 1, 1) Then
        Rows(i + 1).Insert
        Cells(i + 1, 1) = Cells(i, 1) + 1
    End If
    i = i + 1
Loop Until Cells(i + 1, 1) = "31.10.2016"

End Sub

1条回答
三岁会撩人
2楼-- · 2020-04-16 04:48

Here is the code modified with comments to address your issues

Sub InsertMissingDates()

Dim i As Long
Dim RowCount As Long

i = 4

Do
    'Use less then instead of <> so it doesn't flag duplicate cells
    If Cells(i, 1) + 1 < Cells(i + 1, 1) Then
        Rows(i + 1).Insert
        Cells(i + 1, 1) = Cells(i, 1) + 1
    End If
    'Second check to add value if the next row is blank
    If (Cells(i + 1, 1) = "") Then
        Cells(i + 1, 1) = Cells(i, 1) + 1
    End If

    i = i + 1
'Changed the loop function from cells(i+1,1) to cells(i,1) since you already
'incremented i
'Also made the date check slightly more robust with dateserial
Loop Until Cells(i, 1).Value >= DateSerial(2016, 1, 30)

End Sub
查看更多
登录 后发表回答