如何指定范围而不是偏移量,excel VBA?

时间:2013-10-15 19:11:36

标签: excel vba colors

我想在下面的代码中给出一个范围而不是偏移量。下面的代码将颜色从范围(C5:F11)复制到偏移i集,但我想指定范围(M5:P11)。我尝试过简单地用范围替换偏移但是它不能正常工作。请帮忙

Sub MatchColors2()

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

由于

1 个答案:

答案 0 :(得分:3)

除了您的要求,这也适用于具有多个区域的范围,即非连续范围:

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