How to Convert this Coditional formatting formulas into VBA code - excel

I am having an issue converting my specific formula parameters into VBA code. Ive tried many ways but there always seems to have an issue.
When opening conditional formatting box, I have:
Formula= J5>0. Format: Black font Red fill. Applies to: =$K$5:$K$509.
Ive achived the final result, all I need is to somehow write this into VBA

Here are some hints for your VBA coding:
To get an object representing a range use the Range function: Set myRange = Range("K5:K509") and to avoid ambiguity you can use the Range method defined on the Worksheet class: Set myRange = myWorksheet.Range("K5:K509)"
To access conditional formatting use Range.FormatConditions, e.g. to add a new conditional formatting: Set myFC = myRange.FormatConditions.Add(xlExpression, Formula1:="=...")
To change the style of the cell if the condition matches use the resulting object: myFC.Interior.Color = vbRed

Related

VBA Count values based on font color

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")

Using an Excel object with a conditional

Can you use Excel to store a condition requiring the an object to be inserted in a different field. Example if - cell B1 text = "yellow" then place "Caution Clip Art" in cell B30 and make the background yellow.
I'm thinking of JavaScript where you can just use an "if statement". But I've never run across needing this until now. Open to alternatives for a fairly large spreadsheet wanting to use a graphic or clip art.
Graphic Sat Level
You could just use Conditional Formatting for this:
=IF(B1="yellow",1,if(B1="green",2,0))
Then, highlight the column. On the Home Tab > Conditional Formatting > Icon Sets > and choose one that fits your needs.
If you don't want to see the 0,1,2 values, set them to whatever background color you want. And if you want to set the background to yellow, you can use another Conditional format: Conditional Formatting > Highlight Cell Rules and set it up to color how you want.
I believe you need a user-defined function for this. Luckily, it's a simple one. Make sure it's within a Module.
Function ShowPic(PicFile As String) As Boolean
Dim AC As Range
On Error GoTo Done
Set AC = Application.Caller
ActiveSheet.Shapes.AddPicture PicFile, True, True, AC.Left, AC.Top, 200, 200
ShowPic = True
Exit Function
Done:
ShowPic = False
End Function
You can then call this function with =ShowPic("pathtofile.jpg"). You could also use it within an IF statement. So =IF(A2="yellow",ShowPic("caution.jpg"),IF(A2="green",ShowPic("greenlight.jpg")...
The background color can be changed with conditional formatting.

Storing/loading conditional format info in VBA

is there a way I can store and later restore conditional formatting information? Upon selecting a cell, I want to
1/ store the condformatting of the corresponding column/row in some arrays
2/ delete the condformatting of the corresponding column/row
3/ change InteriorColor of column/row to something nice (so that I see a crosshair)
4/ upon selecting another cell, I want to restore the condformatting of the original column/row and repeat the process from 1/ for the currently selected cell.
I tried something like
Public condFmt1 As FormatCondition
Set condFmt1 = Range("A1").FormatConditions.Item(1)
...
Set Range("A2").FormatConditions.Item(1) = condFmt1
however the last line gives me a runTime error 438 - Object does support this property or method. Im probably assigning wrongly.
After playing around with it for an hour, I've found a way around using FormatCondition values in VBA.
This code copies my "A1" range's conditional formatting, which is set to change the font to bold if the value is TRUE
Sub CopyFormatCondition()
Dim fC As FormatCondition
Set fC = Range("A1").FormatConditions.Item(1)
Range("A2").FormatConditions.Add Type:=xlCellValue, Operator:=fC.Operator, Formula1:=fC.Formula1
Range("A2").FormatConditions.Item(1).Font.Bold = fC.Font.Bold
End Sub
Some properties such as Type, Operator and Formula1 have to be set when the FormatCondition is being initialised, hence why I had to add a FormatCondition to the range's FormatConditions collection.
Other properties (e.g. Font and Interior) can be set after the FormatCondition's Initialization.
Assuming you're using Excel 2007 or higher, you can achieve your goal also with a Non-VBA solution:
Use an empty cell in your worksheet/workbook as a trigger cell and set it to TRUE. For convenience, name this cell DisableConditionalFormatting or similar.
Select the active area of the worksheet (Ctrl-A) and insert a new rule -> use formula to determine which cells to format. As a formula set =DisableConditionalFormatting. No need to alter the format here.
After setting the new rule, make sure to select the checkbox Stop if true in the conditional formatting rule manager
No you can toggle the conditional formatting for the worksheet on and off by changing the cell DisableConditionalFormatting.

Way to apply font style and size to Excel worksheet column of text based on content?

Problem
I have an Excel worksheet with a column of text which is data, and some rules in mind for what text values should be formatted with what font and font size.
Specific Example
Cell A1: "Text"
Cells A2 .. (Col. A): strings of text (from a few words to a few sentences) to be optionally formatted with applicable font and font size
Cell B1: "Type of Text"
Cells B2 ... (Col. B): single-word strings such as "heading", "requirement", "note"
Rules in mind:
If string in Col. B is "heading", make string in Col. A font size 18
If string in Col. B is "requirement", make string in Col. A font Calibri
If string in Col. B is "note", make string in Col. A style "italic"
Constraint
Excel, as a spreadsheet, is all about functional programming (formulas) and parallel processing (recalculation). Yes I can write procedural VBA but, for me it goes against the spirit of spreadsheets (even though procedural programming is so popular that Excel and predecessors have offered that for a long time).
Question
Any ideas on how to do it other than special-purpose VBA procedural programming?
What does not seem to solve
Excel conditional formatting does not solve because it expressly does not allow setting those particular cell attributes.
Excel UDFs (User Defined Functions) do not solve because they do not affect other cells. As expected for functions. And even if I wanted to make a function which duplicates the unformatted text but with a style or size based on value, UDFs do not affect the "environment" - only can return data.
And I found here that I can't even put VBA code as text in Excel worksheet cells and then evaluate the text as VBA -- to make a simple generic VBA procedural processing engine for font style and size VBA statements that I would put in cells in my worksheet.
(If any of this negative information is incorrect, and one of the above will work, please correct me.)
VBA special-purpose, procedural programming example -- what works but trying to avoid
Public Sub IterateThroughRangeSetFontStyleSize()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range
Set wb = Application.ActiveWorkbook
Set ws = wb.Worksheets("myWorkSheet")
Set rng = ws.Range("b2", "b4")
For Each cell In rng.Cells
If LCase(cell.Text) = "bold" Then cell.Offset(0, -1).Font.Bold = True
If LCase(cell.Text) = "italic" Then cell.Offset(0, -1).Font.Italic = True
If LCase(cell.Text) = "large" Then cell.Offset(0, -1).Font.Size = 18
Next cell
End Sub
Some ideas that seem too difficult to me but maybe someone will say how they are not
Configure Excel to allow VBA to write to VBA editor (VBE), read the worksheet column of data, calculate desired font style and size based on the rules, and autogenerate VBA procedural code to then update the font style and size of the column of data
Export or Save As the Excel file as XML, write an XSL style sheet that would format per the rules, open (import?) the XML and tell Excel to use the XSL style sheet
What's Needed
Some outside-the-box, keep-it-simple thinking!
It could be possible to keep data and formatting information separately:
Sheet 1: Data;
Sheet 2: Function describing the cell formatting for a corresponding cell on Sheet 1 (resulting in bgcolor="#ff00ff", font size="3" etc.);
Sheet 3: Data and format merged, giving XSL.
The only VBA needed is to write one UDF for Sheet 2 and the other one for Sheet 3.
I'm not sure if this question is a level or not -- you don't want to write VBA code because "it goes against the spirit of Excel"? VBA was introduced in Excel 5.0, and prior to that there was a procedural macro language. Automation has always been integral to Excel's popularity (and the primary reason for the rise of Lotus 1-2-3 before it).
Bold and italics can be manipulated via Conditional Formatting.
For font size, yes, you'll need to write some code. Perhaps some sample data or indications of the type of data (text, integers, real numbers, ...) will initiate some suggestions.

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