Conditional formatting can be powerful. Here is a tip which helps writing conditional formatting functions. Often you want some format to be determined by the current cell rather than some other cell. In these cases it helps to define a named range called 'Me' which is defined in relative terms (i.e. using RC syntax) as just RC (theoretically R[0]C[0]). Then you can write formulas based on Me.
So the code below defines the name Me and then uses it to color in any cell than is non-empty, the formula is
=(LEN(Me)>0)
VBA source code
- Option Explicit
- Function TryItem(ByVal col As Object, ByVal sItem As String, ByRef pobjReturn As Object) As Boolean
- On Error Resume Next
- Set pobjReturn = col.Item(sItem)
- TryItem = Not (pobjReturn Is Nothing)
- End Function
- Sub UsingMeInConditionalFormatting()
- Dim wb As Excel.Workbook
- Set wb = ThisWorkbook
- Const sWorksheet As String = "Sheet1"
- Dim ws As Excel.Worksheet
- Set ws = wb.Worksheets(sWorksheet)
- Dim objNameMe As Object
- Dim namMe2 As Excel.Name
- If Not TryItem(ws.Names, "Me", objNameMe) Then
- 'Stop
- Set namMe2 = ws.Names.Add(Name:="Me", RefersToR1C1:="='" & sWorksheet & "'!RC")
- Else
- Set namMe2 = objNameMe
- Set objNameMe = Nothing
- End If
- 'Stop
- Dim rngUsedRangeTopTenRows As Excel.Range
- Set rngUsedRangeTopTenRows = ws.UsedRange.Rows("1:10")
- rngUsedRangeTopTenRows.FormatConditions.Delete
- Dim formatCond As FormatCondition
- Set formatCond = rngUsedRangeTopTenRows.FormatConditions.Add(Type:=xlExpression, Formula1:= _
- "=(Len(Me)>0)")
- With formatCond.Interior
- .PatternColorIndex = xlAutomatic
- .Color = VBA.RGB(132, 190, 0) 'grass green
- .TintAndShade = 0
- End With
- End Sub
No comments:
Post a Comment