简体   繁体   English

VBA - 根据工作表标签颜色更改特定单元格值的字体颜色

[英]VBA - Change font color of specific cell value based on a sheet tab color

I have a value in the cell V6 and i want it to change its color if the color of a specific sheet tab called "Test" is red (vbRed).我在单元格 V6 中有一个值,如果名为“测试”的特定工作表选项卡的颜色为红色 (vbRed),我希望它更改其颜色。 I have tried a code but it doesn't seem to change the color of the text in the cell.我尝试了一个代码,但它似乎并没有改变单元格中文本的颜色。 I was wondering what is wrong and what could be done to fix it.我想知道出了什么问题以及可以做些什么来解决它。

Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Test")
If ws.Tab.ColorIndex = vbRed Then
Range("v6").Font.Color = vbRed
End If
End Sub

One way to do this is to use a Boolean variable (I called my variable colortest) to test if the tab color is equal to vbRed or not.一种方法是使用Boolean变量(我称之为变量 colortest)来测试标签颜色是否等于 vbRed。

this sample code turns the font color red if the tab is vbRed, and turns the font color black if the tab is any other color than vbRed.如果选项卡是 vbRed,则此示例代码将字体颜色变为红色,如果选项卡是 vbRed 以外的任何其他颜色,则将字体颜色变为黑色。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim ws As Worksheet, colortest As Boolean
Set ws = ThisWorkbook.Sheets("Test")

colortest = Sheets("Test").Tab.Color = vbRed

If colortest = True Then
    Range("v6").Font.Color = vbRed
ElseIf colortest = False Then
    Range("v6").Font.Color = vbBlack
End If

End Sub

` `

Note: I used Worksheet_SelectionChange so the code runs as soon as you click out of cell vs having to edit a cell as in Worksheet_Change注意:我使用了Worksheet_SelectionChange ,因此代码在您单击单元格时立即运行,而不必像在Worksheet_Change中那样编辑单元格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM