【发布时间】:2016-01-08 23:04:17
【问题描述】:
我的工作簿中有几张工作表。每个工作表在单元格 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
谢谢
【问题讨论】:
-
使用
If WeekDay(Range("U2")) = 7 or If WeekDay(Range("U2")) = 1 then -
嗨,斯科特,我认为你很接近,但没有退出。我认为问题出在每张纸上的单元格 U2 中。第一张表(名为 01)是月份的第一张,编码为 2016 年 1 月 1 日,自定义格式为 mmm,d,yyyy。第二个 sheet2 U2 是 '01'!U2+DayOfMonth-1; DayOfMonth 是 VALUE(MID(CELL("filename"),FIND("]",CELL("filename"))+1,255))。我尝试了 Value(sht.Range("U2")、CInt 和 CDbl,都不起作用。但是,当我将日期硬编码为 2015 年 1 月 2 日、2015 年 1 月 3 日等时,它可以工作。