I am newly learning VBA for MS Excel 2007. I wrote a simple loop to fill in missing days of the week, as follows. So the same lines are repeated for each pair of consecutive days just with names of days changed (I omitted all but two here because it got too lengthy). The only caveat is that I want "New" to be added to the cell to the right whenever a new cell with value "Monday" is created. So there is the extra line i.range("B2").Value = "New"
for the first block.
Sub FillWeek()
For Each i In Selection
If i.Value = "Sunday" And i.Range("A2") <> "Monday" Then
i.Range("A2").Insert
i.Range("A2").Value = "Monday"
i.Range("B2").Value = "New"
i.Range("A2").Interior.Color = 192
End If
Next i
For Each i In Selection
If i.Value = "Monday" And i.Range("A2") <> "Tuesday" Then
i.Range("A2").Insert
i.Range("A2").Value = "Tuesday"
i.Range("A2").Interior.Color = 192
End If
Next i
#And the code continues for all other consecutive days pairs
I selected the leftmost cells below, and the results are given here in columns 2 and 3 (in Excel they were given in columns 1 and 2). I've put the unexpected ones in italics.
Row 1 (Selection) | The result (which just replaced column 1) | (And this was added to column 2) |
---|---|---|
Sunday | Sunday | |
Tuesday | Monday | New |
Wednesday | Tuesday | |
Thursday | Wednesday | |
Sunday | Thursday | |
Wednesday | Friday | |
Saturday | Saturday | New |
Monday | Sunday | |
Wednesday | Monday | |
Tuesday | ||
Wednesday | ||
Thursday | ||
Saturday | ||
Monday | ||
Wednesday |
Unexpected Results
Why was "New" not added just next to Monday, it has been added once next to Saturday, and then it was not added next to Monday once?
Why were Friday not added after Thursday and Sunday not added after Saturday towards the end?
i
variable somewhere? If yes, of what type? – FaneDurui.Range("A2").EntireRow.Insert
and all the time try properly declare the used variables. – FaneDuru