Excel条件格式macros

在这里输入图像说明 我正在尝试在excel中编写一个macros来做一些我需要在excel中做的普通任务。 我需要一个macros,它将根据值范围内的date有条件地格式化值的范围。 它需要是dynamic的,因为每次运行时,范围都会改变大小。 我附上了一张关于最后一张表格应该如何处理的照片,以及为什么要这样写格式的原因。

我对VBA非常陌生,所以我似乎无法弄清楚如何做到这一点,但是在我能够学好VBA以便编写代码之前,需要macros。 有人会介意给我一个这样的例子吗? 谢谢。

这应该让你在正确的轨道上!

Sub Main() '---Variables--- Dim myRange As Range '---Customize--- Set myRange = ThisWorkbook.Sheets(1).Range("A:D") 'The range to be formatted '---Logic--- myRange.FormatConditions.Delete 'Clear 'Rules that are up in the list have higher priority Call FormatRange(myRange, 3, "=AND($D1<TODAY()-2;NOT(ISBLANK($D1)))") Call FormatRange(myRange, 29, "=AND($D1<TODAY()-1;NOT(ISBLANK($D1)))") Call FormatRange(myRange, 45, "=AND($D1<TODAY();NOT(ISBLANK($D1)))") Call FormatRange(myRange, 10, "=$D1=TODAY()") 'Note that you may have to use , instead of ; depending on your localization! 'You can find ColorIndexes from http://dmcritchie.mvps.org/excel/colors.htm End Sub 'A support method that makes creating new conditional formats a little easier Public Sub FormatRange(r As Range, colorIndex As Integer, formula As String) r.FormatConditions.Add xlExpression, Formula1:=formula r.FormatConditions(r.FormatConditions.Count).Interior.colorIndex = colorIndex End Sub 

将代码复制到Visual Basic编辑器(ALT + F11)中一个新的代码模块。 请注意,您可能需要更改“;” 到一个“,”取决于你的本地化! 您可以将范围切换到需要格式化的范围,并修改示例公式以适合您的需求或创build新的公式。

你可以在这里findColorIndexes和关于在这里制作实际公式的信息 。

HTH