Î已经阅读了很多问题,建议我避免使用Select。所以我试图设置一个目标细胞,但我遇到了一个问题:
我想使用For循环填充表格,但每次循环时目标单元格都会更改。例如:
Sub try()
Dim target As Range
Set target = Worksheets("Data").Cells(i, 1)
For i = 1 To 10
target.Value = i
Next i
End Sub
那么我可以使用Range in Loop吗?
如果我在For Loop
中设置目标,我担心它不会比我直接选择循环中的单元格Worksheets("Data").Cells(i, 1)
更快?因为我实际上会有很多目标要使用,所以我希望找到一种更简单的方法来设置目标并每次填充它们而不必逐一设置它们。
很抱歉,如果我发布了重复的问题,因为我没有在网上找到类似的问题或答案。如果您有任何想法,请发表评论。谢谢!
答案 0 :(得分:0)
根据您对“阅读”每行的评论。此代码使用For Each
并检查每个单元格以查看要执行的操作。
Public Sub Test()
Dim rMyRange As Range
Dim rCell As Range
'Define a range on the same sheet.
Set rMyRange = ThisWorkbook.Worksheets("Sheet1").Range("A1:A15,C1:C20,D18,E19:E20")
'Add another range using Union just for the hell of it.
Set rMyRange = Union(rMyRange, ThisWorkbook.Worksheets("Sheet1").Range("F30"))
'Step through each cell in rMyRange and decide what to do based on contents/formatting of cell.
For Each rCell In rMyRange
If rCell = "Colour" Then 'Value is default property.
rCell.Interior.Color = RGB(255, 0, 0)
Else
Select Case rCell.Font.Color
Case 255 'Red
rCell = "Red"
Case 5287936 'Green
rCell = "Green"
Case Else
rCell = "Some Other Colour"
End Select
End If
Next rCell
End Sub