获取 For 循环的嵌套部分,使其与外部一起移动



我有一个循环,它遍历工作表并根据另一个单元格中的内容编辑单元格颜色。

所有这些代码都是从数据库导出的Excel工作表上的MS Access执行的。

For StartingCoumn2 = 11 To 14
Column2 = StartingCoumn2
For startingColumn = 15 To 18 'What columns we looking for
ColumnCalc = startingColumn
For startingRow = StartRow To LastWeekEndRow
If .Cells(startingRow, ColumnCalc).Value = 0 Then
.Cells(startingRow, ColumnCalc).Interior.ColorIndex = 3
ElseIf .Cells(startingRow, ColumnCalc).Value >= .Cells(startingRow, Column2).Value Then
.Cells(startingRow, ColumnCalc).Interior.ColorIndex = 4
ElseIf .Cells(startingRow, ColumnCalc).Value < .Cells(startingRow, Column2).Value Then
.Cells(startingRow, ColumnCalc).Interior.ColorIndex = 44
Else
.Cells(startingRow, ColumnCalc).Interior.ColorIndex = 3
End If
Next startingRow
Next startingColumn
Next StartingCoumn2

我的问题是startingColumnStartingCoumn2完成行时需要移动两个 +1。

例如,我已经填写了代码,希望这在概念上对人们有所帮助

For StartingCoumn2 = 11 To 14
Column2 = 11
For startingColumn = 15 To 18 'What columns we looking for
ColumnCalc = 15
For startingRow = 9 To 12
If .Cells(9, 15).Value = 0 Then
.Cells(9, 15).Interior.ColorIndex = 3
ElseIf .Cells(9, 15).Value >= .Cells(9, 11).Value Then
.Cells(9, 15).Interior.ColorIndex = 4
ElseIf .Cells(9, 15).Value < .Cells(9, 11).Value Then
.Cells(9, 15).Interior.ColorIndex = 44
Else
.Cells(startingRow, ColumnCalc).Interior.ColorIndex = 3
End If
Next startingRow
Next startingColumn
Next StartingCoumn2

当它完成该行并移动到需要编辑的下一列(startingColumn(时,比较列(StartingCoumn2(不会移动,这意味着正在比较错误的列。

For StartingCoumn2 = 11 To 14
Column2 = 11
For startingColumn = 15 To 18 'What columns we looking for
ColumnCalc = 16
For startingRow = 9 To 12
If .Cells(9, 16).Value = 0 Then
.Cells(9, 16).Interior.ColorIndex = 3
ElseIf .Cells(9, 16).Value >= .Cells(9, 11).Value Then
.Cells(9, 16).Interior.ColorIndex = 4
ElseIf .Cells(9, 16).Value < .Cells(9, 11).Value Then
.Cells(9, 16).Interior.ColorIndex = 44
Else
.Cells(startingRow, ColumnCalc).Interior.ColorIndex = 3
End If
Next startingRow
Next startingColumn
Next StartingCoumn2

如何让StartingCoumn2同时移动?我试过下一个startingColumnStartingCoumn2但什么也没发生。

你需要的不是另一个 for 循环。 您只需要一个偏移值。 您正在尝试比较同一行中相隔静态值的两列。 所以不要循环,而只是添加偏移量。

例如,您有:.Cells(startingRow, ColumnCalc).Value >= .Cells(startingRow, Column2)

您需要将所有Column2实例更改为ColumnCalc + 4

然后,每当它移动到下一列时,它都会自动检查偏移列。

最新更新