Excel-遍历表超出范围错误

问题描述

我的代码将遍历一个表并存储D列的单元格颜色,同时还将C列中的值存储为另一个变量。这些变量用于在另一个“主”选项卡上查找形状,并将该颜色更新为存储在CellColor中的颜色。当我添加代码的循环部分时,出现了超出范围的错误(-2147024809(80070057))。
Sub Update()
Dim CellColor As Long
Dim ShapeColor As Variant
Dim rng As Range,Cell As Range
Dim i As Integer

Worksheets("Sheet1").Select
Set rng = Range("C2:C100")
For i = 2 To rng.Rows.Count
CellColor = rng.Cells(RowIndex:=i,ColumnIndex:="D").displayFormat.Interior.Color
ShapeColor = rng.Cells(RowIndex:=i,ColumnIndex:="C").Value
Worksheets("main").Shapes(ShapeColor).Fill.ForeColor.RGB = CellColor
i = i + 1
Next
Worksheets("main").Select
End Sub

enter image description here

enter image description here

解决方法

这里也许使用For Each循环,Offset

Set rng = Worksheets("Sheet1").Range("C2:C100")

Dim cell As Range
For Each cell In rng
    ShapeColor = cell.Value
    CellColor =  cell.Offset(,1).DisplayFormat.Interior.Color
    Worksheets("main").Shapes(ShapeColor).Fill.ForeColor.RGB = CellColor
Next

您的问题的简要说明:

rng.Cells(RowIndex:=i,ColumnIndex:="C")
rng.Cells(RowIndex:=i,ColumnIndex:="D")

不是您认为的单元格,因为它们正在偏移,但从C列开始。他们实际上是指 E F 列。

例如:? Range("C2").Cells(1,"C").Address返回$E$2,而不是$C$2

其他要点:

  • 删除i = i + 1Next是递增i的内容。
  • 避免使用SelectSet rng = Worksheets("Sheet1").Range("C2:C100")