簡體   English   中英

如何基於該工作表上的單元格值更改選項卡的顏色

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

我的工作簿中有幾張紙。 每個工作表在單元格U2中都有一個日期。 我希望所有在U2中具有工作日值的單元格都具有綠色的選項卡顏色,而在U2中具有周末值的工作表的選項卡應為黃色。 我已經找到了如何更改選項卡的顏色,但不知道如何特別地將“ Sheet4”選項卡的顏色告訴綠色。 我正在尋找看起來像這樣的代碼:

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

這是我一直在使用的代碼:

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

謝謝

按照您的要求(“我正在尋找看起來像這樣的代碼:”),您的代碼非常接近。

我只改變了:

  1. 您的日期格式(從“ DDD”到“ DDDD”)
  2. 范圍的拼寫錯誤
  3. 用整數代替制表符顏色代替字符串

與您的代碼最接近的是:

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