Using conditional format in VBA - excel

I am using a loop to put a conditional format in "every 4th row" in "column D". However, I am not able to get the code correct.
I had two seperate things happen. First, I have had the formula show up in the spreadsheet with " " around the formula and the conditional format did not work. So now I am trying to rewrite it using the following code and it tells me compile error expected end of statement.
Any help on how I can get the conditional format of D(i-1)>sum(D(i):D(i+2) shade cell red to work is appreciated.
This is the middle of the For/Next loop where I am trying to shade.
Range("D" & (i - 1)).Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:="D" & (i-1) & "> Sum(D" & i & "D" & (i + 2)")"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
i = i + 4

This worked for me:
Sub Tester()
Dim i As Long, fc As FormatCondition
For i = 2 To 10 Step 4
Set fc = ActiveSheet.Range("D" & (i - 1)).FormatConditions. _
Add(Type:=xlExpression, _
Formula1:="=D" & (i - 1) & "> Sum(D" & i & ":D" & (i + 2) & ")")
fc.SetFirstPriority
With fc.Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
fc.StopIfTrue = False
Next i
End Sub

Is it a requirement to do this in VBA? I'm asking because, through regular conditional formatting, you could also easily apply it to every 4th row.
To do so, you simply need a formula like this one in your conditional formatting:
=AND(MOD(ROW($D5),4)=0, $D5 > SUM($D$2:$D4))
The MOD-function divides the row number by 4 and checks if the remainder is 4.
It's not exactly what you asked for, but it might solve your situation...

Related

Use xlExpression with "And" in conditional format

I'm trying to use VBA to give conditional formatting to my table, however my code generates error.
The code is:
Range("M236:P240").Select
Selection.FormatConditions.Add Type:=xlExpression, _
Formula1:="=AND(<$M$241, <7)"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 192
.TintAndShade = 0
End With
When I run it I get an error 5 in the line:
Formula1:="=AND(<$M$241,<7)"
I think it must be a small mistake, maybe I'm missing some parentheses or some quotation marks.
Why is this error generated?
PD: If I change it for:
Formula1:="=AND(M236<$M$241; M236<7)"
The code run, but nothing happens.
I Solved the problem. I had several errors which I mention below:
Thanks to #Scott Craner who mentioned that the formula should not be Formula1:="=AND(<$M$241, <7)" but (M236<$M$241; M236<7)
Secondly my excel for formulas does not use "," but ";".
My excel is in Spanish, so I shouldn't use "AND" but "Y".
try this macro
Option Explicit
Sub colorize_me()
Dim Rg_To_compaire As Range
Dim My_Rg As Range
Dim Single_Range As Range
Dim My_const As Byte: My_const = 7
Set Rg_To_compaire = Range("M241")
Dim My_min#
My_min = Application.Min(Rg_To_compaire, My_const)
If Not IsNumeric(Rg_To_compaire) Then Exit Sub
Set My_Rg = Range("M236:P240")
For Each Single_Range In My_Rg
If IsNumeric(Single_Range) And Single_Range < My_min Then
Single_Range.Interior.ColorIndex = 6
Else
Single_Range.Interior.ColorIndex = xlNone
End If
Next
End Sub

How to write VBA for Do Until last row of data set

I am new to VBA and looking to run a code to colour cells in rows in a specific colour. I have been using DO UNTIL and always end with an extra cell coloured. What is the best way to overcome this.
The table I am working with looks like this,
Number/Name
1/test_01
2/test_02
3/test_03
4/test_04
5/test_05
and continues on and the end will change each time i run the code.
I have set up a test sheet to get the basic idea running so I can expand upon it once I have it running properly. This specific test is dividing column A (Number) by 2 and if there is a remainder of 1 then it will be coloured one way and if not it will be coloured another.
Sub Button2_Click()
Dim row_cnt As Integer
row_cnt = 1
Do Until Sheets("sheet1").Range("A" & row_cnt).Value = ""
row_cnt = row_cnt + 1
If Sheets("sheet1").Range("A" & row_cnt).Value Mod 2 <> 0 Then
Range("A" & row_cnt & ":B" & row_cnt).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = -0.249977111117893
.PatternTintAndShade = 0
End With
Else
Range("A" & row_cnt & ":B" & row_cnt).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent4
.TintAndShade = -0.249977111117893
.PatternTintAndShade = 0
End With
End If
Loop
End Sub
I expect the cells to be coloured until the last cell with a value in. However, this code goes past that and colours an extra cell. I am looking for a way to improve what I have.
you can dynamically find the last row, such that:
lr = cells(rows.count,1).end(xlup).row
row_cnt = 1
Do until row_cnt = lr+1 'so you get actions on your last row
'do stuff
row_cnt = row_cnt + 1
loop
if you can avoid vba for this, bigben's suggestion for conditional formatting would be solid
To answer the specific Q "Why doesn't my Do Untilwork":
It's because you test based on a value of row_cnt , then immediately increment it inside the loop, so process the next row.
To fix that, move the increment to just before Loop and adjust the initialisation of row_cnt
On a side note, you should use Long rather than Integer as the counter data type

Excel VBA editing comment if exists

My code is checking if cell value from 2 sheets are different, if no it continue check for next row, if different it copy from sheet2 to sheet1 the cell value where I need and add to Cell in sheet1(where the value copied too) a comment with the old value.
every time when the value changed again it remove the comment and put new one.
I need to do a comment check if exist and append the old value to comment.
I want that the comment will contain all the old values that changed in the cell.
this is my piece of code:
If Not IsEmpty(datasheet.Cells(iData, j).Value) Then
comm = user & vbNewLine & "Old Date:" & vbNewLine & ActiveCell.Value
datasheet.Cells(iData, j).Copy Destination:=ActiveCell
With ActiveCell
ActiveCell.Interior.ColorIndex = 0
With ActiveCell.Borders
.LineStyle = xlContinuous 'Setting style of border line
.Weight = xlThin 'Setting weight of border line
.ColorIndex = xlAutomatic 'Setting colour of border line
End With
If Not .Comment Is Nothing Then .Comment.Delete
.ClearComments
.AddComment
.Comment.Text Text:=comm
.Comment.Visible = False
End With

Multiple overlapping conditional formatting

I wrote down below code:
Sub formatCondMesi()
Worksheets(1).Unprotect Password:="ponzio"
Dim i As Integer
'For i = 2 To 13
Worksheets(1).Select
Worksheets(1).Cells.FormatConditions.Delete
'1)
With Worksheets(1).Application.Union(Range("C7:O149"), Range("C155:O297"), Range("C303:O445"), Range("C451:O593"))
.FormatConditions.Add Type:=xlExpression, Formula1:="=$H7<0"
.FormatConditions(1).Font.ColorIndex = 3
End With
'2)
With Worksheets(1).Application.Union(Range("J150"), Range("L150"), Range("N150:O150"))
.FormatConditions.Add Type:=xlExpression, Formula1:="=$E150="""""
.FormatConditions(1).Font.ColorIndex = 2
End With
'3)
i = 1
If i = 1 Then
A = Worksheets(1).Range("F4").Value
B = Worksheets(1).Range("F5").Value
End If
With Worksheets(1).Application.Union(Range("E7:E149"), Range("E155:E297"), Range("E303:E445"), Range("E451:E593"))
.FormatConditions.Add Type:=xlExpression, Formula1:="=OR($E7<" & A & ";$E7>" & B & ")" '43101 43131
'.FormatConditions(1).SetFirstPriority = True
.FormatConditions(1).Font.ColorIndex = 3
.FormatConditions(1).Font.Bold = True
.FormatConditions(1).Font.Strikethrough = True
End With
'4)
With Worksheets(1).Application.Union(Range("O7:O149"), Range("O447:O593"), Range("O299:O445"), Range("O151:O297"))
.FormatConditions.Add Type:=xlExpression, Formula1:="=$O7=0"
.FormatConditions(1).Font.ColorIndex = 3
End With
'5)
With Worksheets(1).Application.Union(Range("L7:L149"), Range("L151:L297"), Range("L299:L445"), Range("L447:L593"))
.FormatConditions.Add Type:=xlExpression, Formula1:="=ISNA($L7)"
.FormatConditions(1).Font.ColorIndex = 2
End With
End Sub
I have two issues:
when I reach CF n. 3 ('3) it wrongly apply formats, the strike-through line is applied in another rule and bold style too..and i can't understand with which criteria it is selecting other CF
when I reach CF n.4 it returns:
1004 error, object not defined
For issue 1), probably you have to add
.FormatConditions(1).StopIfTrue = True
else, all conditional formatting rules will be checked and applied
For issue 2): Do you work by any chance with Excel 2003? There, the max. number of rules was limited to 3, so maybe that's your issue. Else I have no idea, I made a quick test and could add more than 3 rules without problem.

Selecting a specific row based on a cell value

This might be a trivial question for you experts out there:
Based on the input (Week) the table is initially filtered on that specific week(WK) and the next one(WK+1).
I'm then formatting all WK+1 cells to be greyed out.
So far so good. Now the question. How can I change the code below so that the entire row containing a cell with the WK+1 value to be greyed out?
ActiveSheet.Range("B5").AutoFilter Field:=1, Criteria1:=WK, Operator:=xlOr, _
Criteria2:=(WK + 1)
With ActiveSheet.Range("$B:$B").FormatConditions _
.Add(xlCellValue, xlEqual, "=" & WK + 1)
With .Font
.Bold = True
.ColorIndex = 15
End With
End With
Thanks in advance!
Mac
This is possible with FormatCondition of type xlExpression.
Example:
ActiveSheet.Range("$A:$Z").FormatConditions.Delete
ActiveSheet.Range("A1").Activate
With ActiveSheet.Range("$A:$Z").FormatConditions _
.Add(Type:=xlExpression, Formula1:="=($B1=" & WK + 1 & ")")
With .Font
.Bold = True
.ColorIndex = 15
End With
End With
I delete the FormatConditions before I add the new one. Because if not, multiple calls of this code would result in multiple FormatConditions ever with the same condition but possible other values of WK. This is because the code adds a new FormatCondition everytime it runs.
Greetings
Axel

Resources