简体   繁体   English

如何基于该工作表上的单元格值更改选项卡的颜色

[英]How to change the color of a tab based on cell value on that sheet

I have several sheets in workbook. 我的工作簿中有几张纸。 Each sheet has a date in cell U2. 每个工作表在单元格U2中都有一个日期。 I would like to have all of the cells with a weekday value in U2 to have a tab color of green, and the tabs of the worksheets which have a weekend value in U2 to be yellow. 我希望所有在U2中具有工作日值的单元格都具有绿色的选项卡颜色,而在U2中具有周末值的工作表的选项卡应为黄色。 I have found how to change the color of the tab, but don't know how to specifically tell it "Sheet4" tab color green. 我已经找到了如何更改选项卡的颜色,但不知道如何特别地将“ Sheet4”选项卡的颜色告诉绿色。 I am looking for the code to look like: 我正在寻找看起来像这样的代码:

For each sht in Thisworkbook.worksheets
  If format(sht.Renge("U2"),"DDD") = "Saturday" _
    or format(sht.Renge("U2"),"DDD") = "Sunday" then
    sht.Tab.ColorIndex = "yellow"
  else
    sht.Tab.ColorIndex = "blue"
  end if
Next

Here is the code I have been working with: 这是我一直在使用的代码:

Sub sbColorAllSheetTab()
    'Declaration
    Dim iCntr, sht As Worksheet

On Error GoTo ErrorHandler

    'Holds the colorIndex number
    iCntr = 2

    'looping throgh the all the sheets of the workbook
    For Each sht In ThisWorkbook.Worksheets

        'Debug.Print Format(sht.Range("U2"), "DDD")  'Tried to check value on sheet - failed
        iCntr = iCntr + 1

        'Applying the colors to Sheet tabs - works
        sht.Tab.ColorIndex = 10 'iCntr

        'Tried to print the value, but didn't work'
        'If I can confirm it sees the correct value in the sheet I can interrogate the value
        'Debug.Print sht.Name  '.Range("U2")
        Debug.Print sht.Range("U2") 'Failed
    Next

   Exit Sub
ErrorHandler:
   ' Error handling code
   Beep
   Resume Next
End Sub

Thanks 谢谢

In the spirit of your request ("I am looking for the code to look like:"), your code was very close. 按照您的要求(“我正在寻找看起来像这样的代码:”),您的代码非常接近。

I only changed: 我只改变了:

  1. Your date format (from "DDD" to "DDDD") 您的日期格式(从“ DDD”到“ DDDD”)
  2. A misspelling of Range 范围的拼写错误
  3. Substituted the integer for the tab color in place of your string 用整数代替制表符颜色代替字符串

The closest thing to your code that I got to work is: 与您的代码最接近的是:

For Each sht In ThisWorkbook.Worksheets
  If Format(sht.Range("U2"), "DDDD") = "Saturday" _
    Or Format(sht.Range("U2"), "DDDD") = "Sunday" Then
    sht.Tab.ColorIndex = 6 'yellow
  Else
    sht.Tab.ColorIndex = 5 'blue
  End If
Next

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

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