Forum Discussion
Excel Autofill by color
In the attached file you can select e.g. range B3:E25 with the mouse. Then you can run the macro in order to select cells with light green color and bright red color and insert a function with dynamic reference location in these cells.
Sub formula()
Dim Cell, selectedrange As Range
Set selectedrange = Selection
For Each Cell In selectedrange
If Cell.Interior.ColorIndex = 48 Or Cell.Interior.ColorIndex = 3 Then
Cell.FormulaR1C1 = "=MATCH(RC1,RC6:RC10,0)"
Else
End If
Next Cell
End SubThe Interior.ColorIndex of the cells with light green color is 48 and the Interior.ColorIndex of the cells with bright red color is 3. You can use the user definded function GetInteriorColorIndex() in order to return the Interior.ColorIndex of a cell. Below is the code of GetInteriorColorIndex().
Function GetInteriorColorIndex(Cell As Range)
Dim StringColor As Integer
StringColor = Cell.Interior.ColorIndex
GetInteriorColorIndex = StringColor
End FunctionIn cell B2 of the attached file i've entered GetInteriorColorIndex() in order to return the Interior.ColorIndex of a cell with light green color.
The cells with light green color or bright red color are scattered in a small sample range in the attached file which could be similar to what you are looking for. Perhaps you can attach a sample file without sensitive data and share the formula which you want to insert in the red or green cells.
I think the same result can't be achieved by dragging a formula across a range because VBA is required to identify the background color of a cell and dragging a formula would enter the formula in cells with other background color as well.