VBA Count values based on font color - excel

I need to add values of a range when its contents are of a certain font color (e.g., black). What I have is a a table where I am conditionally formatting the color of values. For e.g., if the "Status =Carry Over" then I am coloring the row Red. (see attachment).
Now, after the conditional formatting, I want to sum all the number values under a specific column that are NOT in red color.
I have a piece of vba code to add such values, but the problem is, the conditional coloring is throwing the code off. As long as I am manually coloring the rows, the code is ignoring the red rows. If I use the conditional coloring option, then even the colored rows are taken into account.
I am calling the below UDF using this formula =ConditionalColorSum(C2:C30)
Public Function ConditionalColorSum(rnge As Range) As Double
' Total only cells with red font numbers
Application.Volatile
Dim Total As Double, cl As Range
Total = 0
For Each cl In rnge.Cells
If cl.Font.Color = vbRed Then 'Change 'vbRed' to the color you want
Total = Total + cl.Value
End If
Next
ConditionalColorSum = Total
End Function
The Conditional formatting formula looks like above:

As per THIS
Actions such as changing the conditional formatting or table style of a range can cause what is displayed in the current user interface to be inconsistent with the values in the corresponding properties of the Range object. Use the properties of the DisplayFormat object to return the values as they are displayed in the current user interface.
The only way to get the color due to conditional formatting is to use DisplayFormat
If cl.DisplayFormat.Font.Color = vbRed Then
But per THIS
Note that the DisplayFormat property does not work in user-defined functions.
So one cannot use UDF to count the colors directly from the sheet. One can use a SUB but it would be easier just to use the same criteria that the custom format uses to count:
=COUNTIF(E2:E30,"Carry Over")
or to count where it is not red:
=COUNTIF(E2:E30,"<>Carry Over")

Related

Excel code to link range cells' colour into another

I am building a residential stacking plan in which each cell = unit type with specific color given conditional formatting.
2 tables follow below for each unit reflect a sqm size and a $ value.
I need to reflect only the cells' color into the following tables.
I need a dynamic solution and would prefer avoiding vba (since I'm not proficient), but will use if necessary. Thanks in advance!
Find Image HERE
Set up your Conditional formatting as normal on the first table like this:
Note my table starts at cell C4 but yours is in a different place and should be adjusted accordingly. make sure you DON'T have the $ symbol on the formula in the rule but you do have it on the 'Applies to' section
Now copy and paste this formatting onto the second table.
Finally edit the formulas in the conditional formatting so that they point to the starting cell of the FIRST table. It should look like this:
Note that the formatting 'Applies to' the second table but refers in the Formula to the values in the first table.
The result is this:
You can repeat this for other tables if you need to.
As you are working in Excel 2003(!), follow the following steps:
Select the cells in the second table.
In the menu, choose Format - Conditional Formatting.
In the Conditional Formatting box, choose Formula Is.
In the text box, enter the cell reference of the FIRST table (eg C4="4+"), do not enter any $ symbols.
Click the Format button and select the background fill to match the one in the first table.
Add the other conditions in the same way by clicking the Add>> button.
If you change the color code values (B21:B26) from 2 rooms to 2 (to match your second table), the following should do the trick. Basically, this code is not using conditional formating. Getting the color from conditional formating can be somewhat laborious and tricky (google "excel vba find color conditional formatting"). Instead, the present code reads the color in your Color Code cells, and apply it to the other two ranges.
Private Sub BckgndColor()
Dim ColorCodeRange As Range
Dim NoOfRooms As Range
Dim CellColorIndex As Integer
Dim c As Range
Dim d As Object
Set ColorCodeRange = Worksheets("Sheet1").Range("B21:B26")
Set d = CreateObject("scripting.dictionary")
'Add the pairs (value, color) to dictionary
For Each c In ColorCodeRange.Cells
d.Add c.Value, c.Interior.ColorIndex
Next
Set NoOfRooms = Worksheets("Sheet1").Range("M25:V36") 'Here the range of Table 2 (M25:V36 in your example)
'Scan range, and assign color
For Each c In NoOfRooms.Cells
If d.Exists(c.Value) Then
c.Interior.ColorIndex = d(c.Value)
c.Offset(16, 0).Interior.ColorIndex = d(c.Value) 'If Table 3 is always 16 rows down, this shoud work
End If
Next
Set d = Nothing
End Sub
I gave the option data validation list in sheet 2, while I selecting the option by list the cells will change . for that cells I want to get color also from source table in sheet1 to sheet2 .

Obtain cell fill color and delete cell values based on that color

I am new completely new to coding in excel (2013) VB and I need to write some code to do the following:
I have a 2013 workbook with multiple tabs. I need to delete values (could be hard coded numbers, categorical data [e.g., "Yes/No"], or formulas) from only SOME of these tabs (let's say tabs X and Y) based upon cell fill color.
1) First, how do I obtain the color index or, more specifically the color index property (I might not be using the exact correct terminology here)? I assume I need to get this exact number from a function and then plug this number into some sub to delete the conditioned values.
2) Then, how do I use that value to write a sub (?) that will delete all the values in that specific cell color for tabs X an Y?
Any help would be much appreciated.
Thanks.
A cell's color property is held in the cell's interior object. To get the color from cell B3 in Tab 'X' you could do:
Dim cellColor as Long
cellColor = Sheets("X").Range("B3").Interior.Color
Now the cell's color is held in variable cellColor.
This color property is a little oddball though. It's a numeric representation of the RGB, taking the form: (R*256^2 + G*256 + B) Kind of like a bitmask, but at the byte level. Check out the function in the second answer here for a great way to get at these values if you need them.
Really your best bet is to paint a cell, then run a macro to tell you what the color code is.
Pretending like you want to delete everything in Sheet X Range A1:Z5000 that are colored red (65535), you could do something like:
Dim checkCell as Range 'cells are range objects
For each checkCell in Sheet("X").Range("A1:Z5000").Cells 'loop through all the cells assigning the cell in each iteration to variable checkCell
If checkCell.Interior.Color = 65535 Then 'is it red?
checkCell.ClearContents 'null out the value
End If
Next checkCell

Background formatting pairs of rows in a spreadsheet

I was needing a way to format alternating pairs of rows in a worksheet with the same background color. When looking around I found the below link:
Excel VBA: Alternate Row Colors in Range
My problem is similar except that instead of wanting every other row auto filled with a background color I need adjacent pairs of rows colored. For instance, from my start point at row 4 columns A:T would be filled, row 5 columns A:T would have the same background color, rows 6 and 7 columns A:T would be without background color, rows 8 and 9 would share the background color as rows 4 and 5, repeated until the end of the spreadsheet.
I've made an attempt at using conditional formatting for this purpose but 1) I had not been able to get the background alternating for every pair of rows from my start point and 2)it overrides the few special cases that have a different background color 3) conditional formatting does not allow me to manually format any rows that the conditional formatting function formatted.
Many thanks to the commenters for their suggestions (which put me on the right track) but due to the limitations of Conditional Formatting I cobbled together the following Macro that allows the background to be formatted to my needs without eliminating the ability to correct for special cases. The code is heavily commented to help other newbies to understand what the code means and what to modify to change the behavior of the Macro.
Sub AlternateRowColors()
''PURPOSE: To format the background color of alternating pairs of rows in a designated range of cells with values.
'' A correction to account for a possible empty row at the end of the range not having a value failing to follow the
'' desired pattern is included.
'' Example: Column A
'' Row 1: Green
'' Row 2: Green
'' Row 3: No Background Color
'' Row 3: No Background Color
'' Repeating this pattern until the end of the used cells of a worksheet.
Dim lastUsedRow As Long ''Variable to hold the last row number.
lastUsedRow = Range("A200").End(xlUp).Row ''This checks backwards from cell A200 to A1 for the last row with an entry in Column A
''and saves the row number in variable lastUsedRow. Modify this as needed for each worksheet.
If lastUsedRow Mod 2 = 0 Then ''This block of code corrects for the second row of an entry not being highlighted at the
lastUsedRow = lastUsedRow + 1 ''end of the worksheet if the first cell in the following row is blank.
Else
End If
For Each cell In Range("A4:T" & lastUsedRow) ''Sets the range of rows and columns that the background color formatting is to affect.
If cell.Row Mod 4 = 0 Then ''Highlight row if the row number has a divided remainder of zero
cell.Interior.ColorIndex = 35 ''Sets background color by using .ColorIndex instead of RGB. Change to suit your need.
Else
If cell.Row Mod 4 = 1 Then ''Highlight row if the row number has a divided remainder of 1
cell.Interior.ColorIndex = 35 ''Sets background color by using .ColorIndex instead of RGB. Change to suit your need.
End If
End If
Next cell
End Sub
''ADDITIONAL NOTES:
''NONE
Try these formulas in conditional formatting > using a formula to determine which cell's to format:
=AND(ROW()>3,MOD(ROW(),4)=1)
and
=MOD(ROW(),4)=0
both would apply to $A:$T
Put your rules for specially formatted cells after these general rules.
Hope this helps.
In conditional formatting use the formula
=Mod(Row(),4) < 2
in the cells you want the rules to apply to

Excel formula that reads a color in one cell and puts a value in another based on that color

I am trying to set up an if statement formula that will read the color of one cell and place a value in another based on that color. I have tried writing several if statements to do this but cant find one to read the color. The sheet is set up to read a date cell. I have conditional formatting set up to color my weekends. I need a value "200" to show on days that are not on weekends and "0" to show on weekends.
If you were able to do the conditional formatting, you should be able to use a similar formula to input the value. I am guessing it reads the date cell, figures if it is the weekend or not and then inputs the value.
Assuming, for example, the non-weekends are Red (vbRed) then create a UDF (VBA, Add Module and paste the following:
Public Function checkColor(cell)
If cell.Interior.Color = vbRed Then
checkColor = 200
Else
checkColor = 0
End If
End Function
To use the function:
For example to check A1 and put 0 or 200 in B1, in B1 type
=checkColor(A1)

Reference text color in conditionall formatted cells

What we are trying to accomplish is to reference text color in conditionally formatted cells that meet a certain metric. We have a for loop that checks the text color of each cell going down a row.
Colored cells done via conditional formatting can't be referenced via font.color as manually/VBA colored cells are (as far as I know), so we are looking for a way to reference the conditionally formatted color/look in the formatting function and grab the color.
Dim rstarpos As Long
Dim cstartpos1 As Long
rstartpos = 9
cstartpos1 = 3
For i = rstartpos To 10
Sheets("Scorecard").Select
Cells(i, cstartpos1).Select
MsgBox Cells(i, cstartpos1).Font.Color
Font.color would ideally report what the font color of the cell in the loop is. However, because of the conditional formatting it's not. Is there a way to call the conditionally formatted cell's color?
Thanks for your help.
If you're using Excel 2010, you can use the DisplayFormat property of a range to get its displayed format, including the effects of conditional formatting (and table styles). In your example, the last line would change to:
MsgBox Cells(i, cstartpos1).DisplayFormat.Font.Color
Hope this helps.

Resources