Macro for removing conditional formatting fill color Red - vba

I have a large excel report and I am trying to make life easier for my technicians.
I have cells where if a number is not within 10% of another cell then that cell will highlight in RED. My problem is I do NOT want my customers to see the red highlight in my report. I have to convert my excel reports to PDF.
Is there a Macro code that would only take out the conditional formatting for highlight RED?
I have other conditional formatting in my report and that's why I cannot use the Macro code that deletes all conditional formatting.
Also, is there a Macro code that will make it go back to RED?
Any help on this is appreciated. Thanks

The answer is yes. First you need to identify the range you're working on.
Then check if your range has formatting, delete if yes, apply otherwise (like a toggling).
Below code does just that. Change the lines I've commented and adapt. HTH.
Sub ColorUnColor()
Dim myformat As String
Dim cfr As Range
myformat = "=A1<(0.1*B1)" '~~> change to suit
With Sheet2 '~~> change to suit
Set cfr = .Range("D1:D10") '~~> change to suit
If cfr.FormatConditions.Count = 0 Then
.Range("A1").FormatConditions.Add xlExpression, , myformat
With .Range("A1").FormatConditions(1)
.Interior.Color = RGB(255, 0, 0)
.ModifyAppliesToRange cfr
End With
Else
cfr.FormatConditions.Delete
End If
End With
End Sub
Result:
Important: You can assign conditional formatting in any Range, but it will be applied to what you set in ModifyAppliedToRange which I discussed in here.

You could use this to clear any cell on the sheet that is colored red (255). Not sure if that's exactly what you need.
Sub testes()
Dim SrchRng As Range
Set SrchRng = ActiveSheet.UsedRange
For Each Source In SrchRng
If Source.Interior.Color = 255 Then
Source.Interior.Color = xlNone
End If
Next Source
End Sub
As for going back to red couldn't you just run the macro you already have?

Try this:
Selection.FormatConditions.Delete

Related

VBA Color row cells if they are unequal to blank

I'm using the code shown below to essentially make the first row of the spreadsheet color grey based on if the cell is empty or not. For example Cell A1 is not blank so color it grey, cell B1 is not blank so color it Grey but cell C1 is blank so don't color it at all. So far my script colors the whole row grey based on A1. Is there an alternative for this?
Sub test()
Dim c As Integer
c = Application.WorksheetFunction.CountA(ActiveSheet.Range("A1"))
If c > 0 Then
ActiveSheet.Range("A1").EntireRow.Interior.ColorIndex = 48
End If
End Sub
When working with Excel-VBA, it's enourmously helpful to grasp the idea of Objects and Collections and how to loop them.
The Watch-window is your best friend here, as is the With keyword when writing code.
In your case:
a Cell is an object inside the Worksheet.Cells-collection (in your case, also an object inside the ActiveSheet.Rows(1).Cells-collection.
This does what you want, based on the information you gave us (you didnt specify that you do NOT want to loop the whole row ;) )
Option Explicit
Sub ColorCells()
Dim objCell As Object
With ActiveSheet
With .Rows(1)
For Each objCell In .Cells
With objCell
If .Value > 0 Then .Interior.ColorIndex = 48
End With
Next objCell
End With
End With
End Sub
This should give you an idea how Excel-Objects work.
Obviously, we can write this shorter:
Sub ColorCells()
Dim objCell As Object
For Each objCell In ActiveSheet.Rows(1).Cells
If objCell.Value > 0 Then objCell.Interior.ColorIndex = 48
Next objCell
End Sub
Note:
This code will loop all 16k Cells in your Row. Obviously, we could stop at your last used Cell. However, since this runs in under a second, i left that out on purpose to keep the code clean
While you could do this with conditional formatting, i support the idea of doing this with code ONCE, with no traces (that is, your conditional formats), left.
I understand what you tried to do with .CountA and .EntireRow, this doesnt work here.

Find cell with conditional formatting

I have conditionally formatted a worksheet to change the color of cells if values are in error. This is for data validation where the user may cut and paste large amounts of data into the worksheet at once.
I want to write a macro (which I will link to a button) to find and go to the first cell with conditional formatting, then the next, etc. So far, no luck. If this is ultimately not possible, I may just remove conditional formatting and have a macro change cell color so that it can be more easily detected with VBA.
I can detect if there is any conditional formatting with
If ActiveCell.DisplayFormat.Interior.Color <> 16777215
but am having trouble putting it into a find sub.
To be more specific, columns A - AF have values and are formatted red if they do not meet conditions. I'd like a duplicate of the find button but for conditional formatting. Does anyone have any suggestions. I've seen similar questions but they seem to be asking for counts or totals and that's not really what I need. Thanks in advance.
Here is a function that returns an array of cell address that have been conditionally formatted with light red background. Edit to suit your purpose.
Public Function FindConditionals() As Variant
Dim ws As Worksheet, cCell As Range, cntr As Integer
Dim formattedCells(100) As Variant ' I would used the number of cells in used range here
Set ws = ActiveSheet
cntr = 1
For Each cCell In ws.UsedRange
If cCell.DisplayFormat.Interior.Color = 13551615 Then ' put your own color in
formattedCells(cntr) = cCell.Address
cntr = cntr + 1
End If
Next cCell
FindConditionals = formattedCells
End Function
Use the "Go To Special" feature in Excel.
On the Home ribbon, click Find and Select > Go To Special.
Then select the option for Conditional Formats. Click OK and all cells with conditional formats will be selected.

Non selected cells being affected when using Selection.SpecialCells(xlCellTypeVisible)'

I have created a macro that adds a prefix to the current selection. It's pretty simple as you can see - it loops through visible cells in the selection. I added the .SpecialCells(xlCellTypeVisible) because it was affecting unintended cells when using filters.
Sub Prefix()
Dim rng As Range
Dim Prefix As String
Prefix = "P"
For Each rng In Selection.SpecialCells(xlCellTypeVisible)
rng = Prefix & rng
Next rng
End Sub
As an example, assume that my data is Cells A1:A4 filled out like this:
Title
1
2
1
My problem occurs when I do the following:
Put an Autofilter on the range, and hide the '2' that is in A3
Select A2 (the first '1')
Run my macro
The problem is that instead of affecting only Cell A2 (the selected cell), it starts applying the prefix to the first row (A1:Z1 , etc.) until I cancel the macro. It will keep doing this to thousands of cells if I let it keep running.
This problem doesn't happen when my selection is multiple cells, or if I use Selection rather than Selection.SpecialCells(xlCellTypeVisible), or if I apply the macro to one cell when nothing is being filtered out (hidden).
Does anyone have any ideas why the selection defaults to the whole spreadsheet when I only have one cell selected?
Alternatively, can anyone suggest a way to add prefixes like this using VBA?
I am aware that using an excel formula would alleviate the problem but that is not practical for me and regardless is not as fast as clicking a macro.
You can use 'Application.intersect' to make sure you get your desired result:
For each rng in Application.Intersect(Selection,ActiveSheet.Cells.SpecialCells(xlCellTypeVisible))
If you want this to work dynamically when you select a range of cells manually AND your intent is to just prepend the country code from the input box to the current value of the cell, then add the change event posted below to the code section of your worksheet and add the routine to a code module in the workbook.
Not sure why you are doing the replace of the minus sign, but you can add it to this code if needed.
Worksheet code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Call AddPrefix(Target)
End Sub
Add a module and put this code in it.
Sub AddPrefix(rangeToPrefix)
Dim cCell As Range
Dim prefix As String
prefix = InputBox("Enter your country code", "Set Country Code", +33)
For Each cCell In rangeToPrefix.SpecialCells(xlCellTypeVisible)
If Not IsEmpty(cCell) Then cCell.Value = prefix & cCell.Value
Next cCell
End Sub

Excel VBA conditional formatting auto-change

Question:
Is there anything that would cause the Formula1 parameter of the FormatConditions.Add method to change automatically, or to change from what is hard-coded in an Excel-VBA macro?
If so, where is the documentation for this behavior?
Description of Problem:
When applying the FormatConditions.Add method to a range, the formula does not match what is specified in the code.
My macro code assigns a formula to a variable named ConditionalRangeFormula. After running the macro the actual conditional formatting formula does not match ConditionalRangeFormula, and the row in the formula does not match the row that was specified in the code. See the "Details" section below for more info.
Hypothesis:
Note 1:
I've noticed that with a range, Excel will automatically "fit" a conditional formatting formula to match the specifics for each cell in a range. For example, in a worksheet with random numbers between 1 and 10 in column A:
I choose column A.
I add a conditional format to column A, with a formula "=IF(A1=2,1)". The cell font is formatted bold red if this formula is true.
Every cell in column A that contains "2" will be bold red, not just cell A1, even though the formula is just for A1.
Is it possible that in the background Excel is doing some changing of my formula in the code above, in an attempt to "guess" what the formula actually should be?
Note 2:
I don't think this is a result of using too many conditional formats for a range. In Microsoft's Excel developer notes for "FormatConditions.Add Method", there is a remark that "You cannot define more than three conditional formats for a range." However, I've successfully added more than three conditional formats with no changes (see details below). Also, I've tested with all other conditional formatting commented out (inactivated), so that only one conditional format is applied, with no changes.
Details:
I'm using Excel 2007 on a Win7 machine.
My code is a little more complex than the example given in the hypothesis above.
The conditional format function is designed to check if a cell in column "AP" is blank, then apply a red outline.
If I place a breakpoint at the With conditionalRange.FormatConditions _.add(xlExpression, , ConditionalRangeFormula) line, I can confirm ConditionalRangeFormula is correct ("=ISBLANK($AP1)"). However, after running, the conditional formatting formula for every cell in the specified range is "=ISBLANK($AP2)". This does what my code specifies.
Please note the working range (ConditionalRange is the code below) actually starts with row 2 of column AP, since row 1 is a header row. As an interesting note, if I make ConditionalRangeFormula "=ISBLANK($AP2)", the conditional formatting formula for every cell in the specified range is "=ISBLANK($AP3)". Notice how the row in the formula is +1 from what is hard coded, just as in the first situation described in the previous paragraph. Interesting behavior, but I can't find documentation for this.
Also, please note that there are four With...End With statements that apply conditional formatting to that cell, before the conditional formatting that gives problems is applied. Each of those first four statements use formulas that work as expected, so I've simplified those code blocks to make the overall code easier to follow. See "Note 2" under the Hypothesis section above for more details.
Here is the code outline:
'define string to identify workbook
Dim w2 As String
w2 = "myworksheet.xlsx"
'define ws2 as worksheet to work on
Dim ws2 As Worksheet: Set ws2 = Workbooks(w2).Worksheets(1)
'define working range
Dim ws2r As range
Set ws2r = ws2.range("E2", ws2.range("E2").End(xlDown))
'add conditional formatting to the working range
With ws2
'see below for .colDiff function
Set ConditionalRange = ws2r.Offset(0, colDiff("E", "AP"))
'The following 4 With...End With statements assign other
'conditional formats, none of which have problems.
'I've simplified these statements to outline what's being done.
'See the last (5th) With...End With statement for
'the unexpected behavior.
WithConditionalRange.FormatConditions _
.add(xlExpression, , ADifferentFormula1)
.Font.Color = someRGBValue
End With
WithConditionalRange.FormatConditions _
.add(xlExpression, , ADifferentFormula2)
.Font.Color = someRGBValue
End With
WithConditionalRange.FormatConditions _
.add(xlExpression, , ADifferentFormula3)
.Font.Color = someRGBValue
End With
WithConditionalRange.FormatConditions _
.add(xlExpression, , ADifferentFormula4)
.Font.Color = someRGBValue
End With
'This With...End With block has unexpected behavior.
ConditionalRangeFormula = "=ISBLANK($AP1)"
With ConditionalRange.FormatConditions _
.add(xlExpression, , ConditionalRangeFormula)
.Borders.color = RGB(192, 0, 0)
End With
End With 'with ws2
Here's the "colDiff" function called in the procedure above:
Public Function colDiff(col1 As String, col2 As String) As Long
With ActiveSheet
'return the number of columns between col1 and col2
colDiff = Abs(.range(col1 & "1").Column - .range(col2 & "1").Column)
End With
End Function
I tested this functionality by placing a header "Data" in AP1, placing random data from AP2 to AP16, then deleting AP1,5,7,13 to make BLANKS and the following worked correctly:
Public Sub Test()
With Range("E2:AP16").FormatConditions.Add(xlExpression, , "=ISBLANK($AP2)")
.Borders.Color = RGB(192, 0, 0)
End With
End Sub
Does the above single function work correctly for you? If not, I would suspect that perhaps there are merged cells or some other spreadsheet specific issue going on.

Change Value in Excel from String to Number

I wrote a script in VBA where numbers from a text file will be inserted into a worksheet. After inserting the values, Excel advises me to convert the values from strings to numbers. Inside the cell, a green triangle appears. After selecting the cell, there are different options you can select to format the value inside the cell.
I also tried to convert the values to double in VBA with CDbl(string) but nothing happens.
Changing the NumberFormat also doesn't work. I tried different values in VBA and also in Excel.
I also tried to record a macro while selecting the method but there was nothing saved inside the makro.
Anybody know how to do this?
Try this. I have taken cell A1 as an example. Also if there are decimal values then instead of Long use a Double and change the NumberFormat accordingly.
Sub Sample()
Dim clVal As Long
With Sheet1.[a1]
clVal = Val(.Value)
.NumberFormat = "0"
.ClearContents
.Formula = clVal
End With
End Sub
It might seem a bit silly, but have you tried Range("A1").Value = Range("A1").Value?
More generally, you can loop through myrange, assuming it is the range you want to fix:
For Each c in myrange
c.Value = c.Value
Next