2014-06-09 146 views
3

enter image description here我想在excel中編寫一個宏來做一些我需要在Excel中做的普通任務。我需要一個宏,它將根據值範圍內的日期有條件地格式化一系列值。它需要是動態的,因爲每次運行時,範圍都會更改大小。我附上了關於最終表格應該如何格式化的原因的照片。Excel條件格式宏

我對VBA非常陌生,所以我似乎無法弄清楚如何做到這一點,但需要宏才能夠充分學習VBA來編寫代碼。有人會介意向我展示如何做到這一點的例子嗎? 謝謝。

+2

在設置CF規則時嘗試錄製宏。然後嘗試編輯代碼。 –

+0

[在Macro/VBA中使用3個條件的條件格式](http://stackoverflow.com/questions/22500483/conditional-formatting-using-3-conditions-in-macro-vba/22501780#22501780)可能會給你一個提示關於如何以編程方式進行。至於獲得動態範圍,你可以在這裏看到很多例子。 – L42

回答

10

這應該讓你走上正軌!

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)。 請注意,您可能需要更改「;」到「,」取決於您的本地化!您可以將範圍切換爲需要格式化的範圍,並修改示例公式以適合您的需求或創建新範例。

你可以找到ColorIndexes here和有關製作實際公式here的信息。

HTH