Home » excel » How to specify range instead of offset , excel VBA?

How to specify range instead of offset , excel VBA?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to give a range instead of offset in the following code. following code copies the color from range(C5:F11) to the offset i set but i want to specify a range like range(M5:P11). I tried it simply replacing offset by range but it does not work properly. Please help

Sub MatchColors2()

For Each myCellColor In Range("C5:F11") 
    myCellColor.Offset(0, 8).Interior.ColorIndex = myCellColor.Interior.ColorIndex
Next
End Sub

Thanks

How to&Answers:

Along with your requirement, this also works for ranges with more than one Area, i.e., non-contiguous ranges:

Sub MatchColors2()
Dim rngTo As Excel.Range
Dim rngFrom As Excel.Range
Dim i As Long
Dim j As Long

Set rngTo = ActiveSheet.Range("C5:D11,F5:G11")
Set rngFrom = ActiveSheet.Range("I5:J11,L5:M11")

For i = 1 To rngFrom.Areas.Count
    For j = 1 To rngFrom.Areas(i).Cells.Count
        rngTo.Areas(i).Cells(j).Interior.ColorIndex = rngFrom.Areas(i).Cells(j).Interior.ColorIndex
    Next j
Next i
End Sub