简体   繁体   English

打开特定日期的VBA Excel单元格格式

[英]VBA Excel Cell formatting on specific days on open

I would like to have a cell range (a9:e13) font colour changed to black if the day is a Monday, and changed to white if it is any other day. 我想让一个单元格范围(a9:e13)字体颜色如果一天是星期一更改为黑色,如果是其他任何一天则更改为白色。 I would like this to execute as the file is opened. 我希望在打开文件时执行此操作。

So far i have 到目前为止,我有

Private Sub Workbook_open()
If Cell(S2).Value = True Then
Range("a9:e13").Font.Color = vbWhite
Else
Range("a9:e13").Font.Color = vbBlack
End If
End Sub

In cell S1 I have= =Today() 在单元格S1中,我有= = Today()

In cell S2 i have= =Weekday(S1) = 2 在单元格S2中,我==平日(S1)= 2

This is not working at all, can someone please help me understand my mistake? 这根本没有用,有人可以帮我理解我的错误吗?

The working Code 工作守则

Private Sub Workbook_open()
If Sheet1.Cells(2, "S") = True Then
Sheet1.Range("a9:e13").Font.Color = vbBlack
Else
Sheet1.Range("a9:e13").Font.Color = vbWhite
End If
End Sub

I think the easiest solution is not using VBA, but using conditional formatting. 我认为最简单的解决方案不是使用VBA,而是使用条件格式。 For example, see http://office.microsoft.com/en-us/excel-help/use-a-formula-to-apply-conditional-formatting-HA102809768.aspx 例如,请参阅http://office.microsoft.com/zh-cn/excel-help/use-a-formula-to-apply-conditional-formatting-HA102809768.aspx

In addition it seems like your code example has some errors, it should look like this? 此外,您的代码示例似乎有一些错误,应该看起来像这样吗? Where Sheet1 must be replaced by name of your sheet. 其中Sheet1必须替换为工作表名称。

If Sheet1.Cells(2, "S") = True Then
    Sheet1.Range("a9:e13").Font.Color = vbWhite
Else
    Sheet1.Range("a9:e13").Font.Color = vbBlack
End If

我将使用以下公式进行条件格式设置:

=WEEKDAY(TODAY())=2

Another alternative is 另一种选择是

Private Sub Workbook_open()
    With Worksheets("Your_sheet_name")
        If Weekday(Now) = vbMonday Then
            .Range("a9:e13").Font.Color = vbWhite
            Else
            .Range("a9:e13").Font.Color = vbBlack
        End If
    End with
End Sub

Edit: @ hnk - true, thanks for bringing this up. 编辑:@ hnk-是的,谢谢提出。 My thinking was that since this was part of the original requirements that any changes occur on workbook opening, and assuming an understanding of the implications involved, I just thought it would be fair to assume the scenario you point out would be unlikely to happen. 我的想法是,由于这是工作簿打开时进行任何更改的原始要求的一部分,并且假设理解了所涉及的含义,所以我认为假设您指出的情况不太可能发生是合理的。 But I acutally may have been better emphasizing that 但我可能会更好地强调这一点

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

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