I'm trying to add a vba section to my project which assigns serial numbers to the coloured range of the first column, however without success. I've come up with the follwing code:
Private Sub CommandButton1_Click()
On Error GoTo ErrorHandler
Dim serial, i, EndRow, StartRow As Integer
Dim row As Range, cell As Range
'Discover the data starting and end rows
i = 1
serial = 1
StartRow = 1
EndRow = 1
'Check the first cell of each row for the data-start background colour
For Each row In ActiveSheet.UsedRange.Rows
Cells(row.row, 1).Select
If i < 3 Then
If Hex(cell.Interior.Color) = "47AD70" And i = 1 Then
Cells(row.row, 1).Value = Abs(serial)
StartRow = serial
serial = serial + 1
i = 2
ElseIf Hex(cell.Interior.Color) = "47AD70" And iRow = 2 Then
Cells(row.row, 1).Value = Abs(serial)
serial = serial + 1
ElseIf Hex(cell.Interior.Color) <> "47AD70" And iRow = 2 Then
EndRow = serial - 1
i = 3
End If
End If
Next row
ErrorHandler:
If Err.Number <> 0 Then
Msg = "Error # " & Str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
End Sub
The variable i is used as a flag to detect the coloured range.
By the end, the green cells A5 to A22 should be filled with numbers 1 to 18. Also variable StartRow should end up being assigned value = 5 (starting row of the coloured range), and EndRow should end up being assigned value = 22 (Ending row of the coloured range.
My code generates Error# 91, Object variable or With block variable not set.
Apart from the error which I'm not able to rectify, I know the code itself is not that clever either and there may be more efficient code to achieving the objective.
Could someone please suggest a resolution or even a better code? Many thanks
I may not fully understand what you are trying to do. The code below will look for the first green cell in column A, give that cell the serial number 1, and continue numbering subsequent green cells serially. I hope that is what you would like.
Note that it's usually dangerous to make changes on the
ActiveSheet
. The danger is in the user's erroneously running the code while the wrong sheet is active. Therefore it's better to modify the above code to specify the intended sheet by name.