View Single Post
  #16   Report Post  
Posted to microsoft.public.excel.programming
Myrna Larson[_2_] Myrna Larson[_2_] is offline
external usenet poster
 
Posts: 124
Default INSERTING ROWS WITH A MACRO

As I said, Jay emailed me about a problem.

I've found a logical error: I was aborting the For/Next loop when I hit the header row. That
meant that rows would never be inserted above row 2, even if A2 doesn't contain the 1st date in
the series, i.e. there are dates missing at the top. (When I tested the code, my first data
block was OK -- my error!)

All blocks must contain 7 dates, so the For/Next loop should never be aborted. The following
code corrects the bug. I also made a change so that if there's no header, only one line of the
code must be changed.

This fix takes care of problems with missing dates at the very top. But Jay said the 1st block
was OK but blocks below not. I can't reproduce that problem.

Option Explicit

Sub AddMissingRows()
Dim D As Long
Dim DateList(1 To 7) As Long
Dim i As Long
Dim R As Long

'change following to 0 if there's no header
Const HeaderRow = 1

DateList(1) = CLng(Range("K1").Value)
For i = 2 To 7
DateList(i) = DateList(i - 1) + 1
Next i

On Error GoTo BadData
R = Cells(65536, 1).End(xlUp).Row
D = CLng(Cells(R, 1).Value)

Do Until R = HeaderRow
For i = 7 To 1 Step -1
If D < DateList(i) Then
Rows(R + 1).Insert
Cells(R + 1, 1).Value = CDate(DateList(i))
Else
R = R - 1
If R HeaderRow Then
'not the header: get next date
D = CLng(Cells(R, 1).Value)
Else
'header: set D = invalid date so if i < 1
'the For/Next loop will complete and insert
'any rows missing at the top
D = DateList(1) - 1
End If
End If
Next i
Loop

Exit Sub

BadData:
MsgBox "Bad data in A" & R
End Sub