I’m trying to run a script that inserts a number in to a cell based on the cell’s color; if the color is red, then insert the # 1. The spread sheet has 380 rows but the script stops running (inserting 1’s) at row 346. Script below:
Sub InsertOne()
Dim endRow As Long
Dim colorD As Range
Dim Cell As Range
endRow = Sheets(1).Cells(Sheets(1).Rows.Count, "C").End(xlUp).Row
'Ensure ending row is at least Row 2
If endRow < 2 Then
endRow = 2
End If
Set colorD = Range("F2", Range("F" & Rows.Count).End(xlUp))
'Loop through each cell in Column D
For Each Cell In colorD
If Cell.Interior.ColorIndex = 3 Then
Cell.Value = 1
End If
Next Cell
End Sub
Try below code :
Once you calculate the endRow, you can use that to Set colorD
range.
Sub InsertOne()
Dim endRow As Long
Dim colorD As Range
Dim Cell As Range
endRow = Sheets(1).Cells(Sheets(1).Rows.Count, "C").End(xlUp).Row
'Ensure ending row is at least Row 2
If endRow < 2 Then
endRow = 2
End If
Set colorD = Range("F2:F" & endRow)
'Loop through each cell in Column D
For Each Cell In colorD
If Cell.Interior.ColorIndex = 3 Then
Cell.Value = 1
End If
Next Cell
End Sub
Tags: excel-vbaexcel, vba