我有一个问题,即将包含颜色和其中某些值的单元格复制到一个范围内。以下代码的问题在于,它会复制粘贴整个范围,而不粘贴红色区域。
Sub testing()
Dim Myrange As Range
Dim Mycell As Range
Dim Target As Range
Set Myrange = Sheet1.Range("A3:A15")
Set Target = Sheet1.Range("B3:B15")
For Each Mycell In Myrange
If Mycell.Interior.ColorIndex = 3 Then
Mycell.Copy Target
End If
Next Mycell
End Sub
我的预期结果是复制在目标范围内仅包含红色的粘贴单元格。 (如果A3单元为红色,我也希望B3单元也为红色。但是我不希望目标单元的整个范围都变成红色)
答案 0 :(得分:0)
如果您打算偏移1:
,则不需要target
范围。
Sub TestMe()
Dim myRange As Range
Dim myCell As Range
Set myRange = Worksheets(1).Range("A3:A15")
For Each myCell In myRange
If myCell.Interior.ColorIndex = 3 Then
myCell.Copy myCell.Offset(0, 1)
End If
Next myCell
End Sub
或者如果出于任何原因需要使用target
,则在这种情况下按索引循环就可以了,因为单元格位于1行:
Sub TestMe()
Dim myRange As Range
Dim myCell As Range
Set myRange = Worksheets(1).Range("A3:A15")
Set target = myRange.Offset(columnoffset:=1)
Dim i As Long
For i = 1 To myRange.Cells.Count
If myRange.Cells(i).Interior.ColorIndex = 3 Then
myRange.Cells(i).Copy target.Cells(i)
End If
Next i
End Sub