每次刷新页面时,遍历更改特定单元格中的字体颜色的范围



我写了这段代码作为开始。我认为我走在正确的道路上,但代码显然需要更多才能工作。本质上,我想从单元格 W8 开始:

如果字体在 W8 中为黑色,它应该移动到 W9 并通过范围(W8、W9、W10、W11、W12、Y8、Y9、
  • Y10、Y11、Y12,然后作为循环返回 W8(检查字体是否为黑色。
  • 如果循环在字体为红色的单元格上停止,则应将其更改为黑色,列表中的下一个单元格应更改为红色。然后它应该退出子。
SubFontW8()
If Range("W8").Font.Color = vbRed Then
Range("W8").Font.Color = xlAutomatic
And
Range("W9").Font.Color = vbRed
Exit Sub
Else
Call SubFontW9()
End If
End Sub

SubFontW9()
If Range("W9").Font.Color = vbRed Then
Range("W9").Font.Color = xlAutomatic
And
Range("W10").Font.Color = vbRed
Exit Sub
Else
Call SubFontW10()
End If
End Sub

SubFontW10()
If Range("W10").Font.Color = vbRed Then
Range("W10").Font.Color = xlAutomatic
And
Range("W11").Font.Color = vbRed
Exit Sub
Else
Call SubFontW11()
End If
End Sub

SubFontW11()
If Range("W11").Font.Color = vbRed Then
Range("W11").Font.Color = xlAutomatic
And
Range("W12").Font.Color = vbRed
Exit Sub
Else
Call SubFontW12()
End If
End Sub

SubFontW12()
If Range("W12").Font.Color = vbRed Then
Range("W12").Font.Color = xlAutomatic
And
Range("Y8").Font.Color = vbRed
Exit Sub
Else
Call SubFontY8()
End If
End Sub

SubFontY8()
If Range("Y8").Font.Color = vbRed Then
Range("Y8").Font.Color = xlAutomatic
And
Range("Y9").Font.Color = vbRed
Exit Sub
Else
Call SubFontY9()
End If
End Sub

SubFontY9()
If Range("Y9").Font.Color = vbRed Then
Range("Y9").Font.Color = xlAutomatic
And
Range("Y10").Font.Color = vbRed
Exit Sub
Else
Call SubFontY10()
End If
End Sub

SubFontY10()
If Range("Y10").Font.Color = vbRed Then
Range("Y10").Font.Color = xlAutomatic
And
Range("Y11").Font.Color = vbRed
Exit Sub
Else
Call SubFontY11()
End If
End Sub

SubFontY11()
If Range("Y11").Font.Color = vbRed Then
Range("Y11").Font.Color = xlAutomatic
And
Range("Y12").Font.Color = vbRed
Exit Sub
Else
Call SubFontY12()
End If
End Sub

SubFontY12()
If Range("Y12").Font.Color = vbRed Then
Range("Y12").Font.Color = xlAutomatic
And
Range("W8").Font.Color = vbRed
Exit Sub
Else
Call SubFontW8()
End If
End Sub

如果您有任何帮助,我们将不胜感激。谢谢。

有几种方法可以完成此任务。首先,您需要一个 For Next 循环。在此上下文中,您可以使用For NextFor Each。我建议阅读更多关于循环的信息,以更好地理解。

为了简单起见,我将使用For Each循环。

请参阅下面的代码(插入 VBE 中的任何普通模块(:

Option Explicit
Sub Change_Font_Colour()

'range where you want to change the font colours
Dim rOperationRange As Range
'variable used to loop through the operation range
Dim cell As Range


'set range object
'you should ALWAYS have a worksheet qualifier
'change the sheet name to the required sheet name and adjust your range accordingly
Set rOperationRange = ThisWorkbook.Sheets("mySheetName").Range("W8:Y12")


'for loop
For Each cell In rOperationRange
If cell.Font.Color = vbRed Then
'set to black
cell.Font.Color = vbBlack
'set cell BELOW as red using .Offset
cell.Offset(1, 0).Font.Color = vbRed
'now exit
Exit Sub
End If
Next cell


End Sub

最新更新