Get Conditionally Formated Cells (DupeUnique = xlDuplicate) - excel

I am highlighting all duplicate cells in my selection using:
Selection.FormatConditions.AddUniqueValues
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Selection.FormatConditions(1).DupeUnique = xlDuplicate
With Selection.FormatConditions(1).Font
.Color = -16383844
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13551615
.TintAndShade = 0
End With
Now I don't just want to highlight those cells, but I want to get an array with all the effected cells. I tried looping through my selection and checking the Interior property, but that takes ages. I'm looking for something way faster.

A function, returning a list (Collection) of all the values in the Excel Selection, corresponding to this condition:
If myCell.DisplayFormat.Interior.Color = myColor Then
would be quite useful:
Sub TestMe()
'...OP Code
.TintAndShade = 0
End With
Dim unique As Collection
Set unique = ResultList(Selection)
If unique.Count > 1 Then Debug.Print unique.Item(2)
End Sub
Public Function ResultList(selectedRange As Range, _
Optional myColor As Long = 13551615) As Collection
Dim myCell As Range
Dim myResultList As New Collection
For Each myCell In selectedRange
If myCell.DisplayFormat.Interior.Color = myColor Then
myResultList.Add myCell.Value2
End If
Next myCell
Set ResultList = myResultList
End Function
Thus, the Selection is avoided and one can use it further.

Related

Executing the VBA code on opening the excel instead of Changing value

I have a VBA code for a Rota Sheet that is activated on change of any value in the row.
I want the code to be activated upon opening the excel.
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Set rng = Range("B2:V11")
If Not Intersect(Target, rng) Is Nothing Then
'scan each row (month)
Dim countRow As Long
Dim i As Long
For i = 1 To rng.Rows.count
If Not Intersect(Target, rng.Rows(i)) Is Nothing Then
If WorksheetFunction.CountIf(rng.Rows(i), "V") > 0 Then
countRow = 0
Dim cel As Range
For Each cel In rng.Rows(i).Cells
If cel.Value2 = "V" Then
countRow = countRow + 1
VacationChange cel, countRow
Else
VacationChange cel, 0
End If
Next cel
End If
End If
Next i
'scan each column (day)
Dim j As Long
For j = 1 To rng.Columns.count
If Not Intersect(Target, rng.Columns(j)) Is Nothing Then
If WorksheetFunction.CountIf(rng.Columns(j), "V") > 5 Then
VacationChange rng.Columns(j).Cells(0, 1), 6
Else
VacationChange rng.Columns(j).Cells(0, 1), 0
End If
End If
Next j
End If
End Sub
Private Function VacationChange(ByVal rng As Range, ByVal count As Long)
With rng.Interior
Select Case count
Case 0
'clear cell colors
.Pattern = xlNone
.Color = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
Case 1 To 3
'blue
.Pattern = xlSolid
.Color = 15773696
.TintAndShade = 0
.PatternTintAndShade = 0
Case 4 To 5
'yellow
.Pattern = xlSolid
.ThemeColor = xlThemeColorAccent4
.TintAndShade = 0.399975585192419
.PatternTintAndShade = 0
Case Else
'red
.Pattern = xlSolid
.Color = 255
.TintAndShade = 0
.PatternTintAndShade = 0
End Select
End With
End Function
I spent efforts by trying:
1. Using below code in Workbook: which is throwing 424 error
Private Sub Workbook_Open()
Sheet1.Activate
Call Worksheet_Change(Target)
End Sub
Pasting the entire code under Workbook_Open() function which is not working
Can anyone suggest what i am missing in the code ?
Sample Output image is attached
enter image description here
The problem is that Target is an undeclared Variant in your Workbook_Open implementation. That means when it gets passed as a parameter that needs to be a Range, the implicit cast fails and results in an error 424 (Object required).
If you want to "simulate" every cell in your target range changing, you can simply loop over B2:V11 and pass it each individual cell (untested with your data, but should give the gist):
Private Sub Workbook_Open()
Sheet1.Activate
Dim cell As Range
For Each cell In Sheet1.Range("B2:V11")
'Worksheet_Change needs to be Public
Sheet1.Worksheet_Change cell
Next
End Sub
Note that this is by no means the ideal solution to what you are trying to do and is a sign that you need to refactor your code a little bit to extract the functionality that you currently have in Worksheet_Change into a free-standing procedure. If you need to run the same code from the Worksheet_Change handler, you can call that procedure.

VBA Excel Highlighting cells based on cell input

I'm trying to create a VBA script to highlight a particular range of cells when a user inputs any value in the cell. For example my cell range will be a1:a5, if a user enters any value in any cells within the range, cells a1 till a5 will be highlighted in the desired color. I'm a new user with VBA and after searching for a while found the below code that might be useful. Looking for advice. Thanks.
Private Sub Highlight_Condition(ByVal Target As Range)
Dim lastRow As Long
Dim cell As Range
Dim i As Long
With ActiveSheet
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
Application.EnableEvents = False
For i = lastRow To 1 Step -1
If .Range("C" & i).Value = "" Then
Debug.Print "Checking Row: " & i
.Range("A" & i).Interior.ColorIndex = 39
.Range("F" & i & ":AW" & i).Interior.ColorIndex = 39
Next i
Application.EnableEvents = True
End With
End Sub
Edit: Trying to edit the code given by teylyn to be able to remove highlight from cells if cell value is removed however I can't seem to find the solution. (The original code will highlight the cells when there is input in cells however if you remove the cell value the highlight remains there.)
If Not Intersect(Target, Range("A12:F12")) Is Nothing Then
With Range("A12:F12").Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ElseIf IsEmpty(Range("A12:F12").Value) = True Then
With Range("A12:F12").Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65536
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
This code does what you describe, i.e. set a fill color for range A1 to A5 when any cell in that range is edited.
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1:A5")) Is Nothing Then
With Range("A1:A5").Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
End Sub
This code needs to be put in the sheet module.
Edit: If you want the highlight to disappear if none of the five cells have a value, then you can try out this variant:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim valCount As Long
If Not Intersect(Target, Range("A1:A5")) Is Nothing Then
' a cell in Range A1 to A5 has been edited
' we don't know if that edit was adding or deleting a cell, so ...
' ... we count how many cells in that range contain values
valCount = WorksheetFunction.CountA(Range("A1:A5"))
If valCount > 0 Then
' the range has values, so highlight
With Range("A1:A5").Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Else
' the range has no values, so remove the highlight
With Range("A1:A5").Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
End If
End Sub

Conditional Formating by groups in excel

Was wondering if there was a way to set conditional formatting separately for different groups across the same column. Something like this:
The idea is that the color scale should be done independently for the groups. In Group 1: 2 is the smallest value and therefore would be red and 50 is the highest and therefore would be green (even though there are values like 114 or 1467, it shouldn't affect this range as it belongs to a different group).
Thanks in advance!
If colour scaling within groups something like:
Public Sub FormatRanges()
Dim rng1 As Range, rng2 As Range, rng3 As Range, rng As Long
Application.ScreenUpdating = False
With ActiveSheet
Set rng1 = .Range("B1:B5")
Set rng2 = .Range("B6:B10")
Set rng3 = .Range("B11:B15")
Dim myRanges()
myRanges = Array(rng1, rng2, rng3)
For rng = LBound(myRanges) To UBound(myRanges)
ApplyFormatting myRanges(rng)
Next rng
End With
Application.ScreenUpdating = True
End Sub
Public Sub ApplyFormatting(ByRef rng As Variant)
rng.FormatConditions.Delete
rng.FormatConditions.AddColorScale ColorScaleType:=3
rng.FormatConditions(rng.FormatConditions.Count).SetFirstPriority
rng.FormatConditions(1).ColorScaleCriteria(1).Type = _
xlConditionValueLowestValue
With rng.FormatConditions(1).ColorScaleCriteria(1).FormatColor
.Color = 7039480
.TintAndShade = 0
End With
rng.FormatConditions(1).ColorScaleCriteria(2).Type = _
xlConditionValuePercentile
rng.FormatConditions(1).ColorScaleCriteria(2).Value = 50
With rng.FormatConditions(1).ColorScaleCriteria(2).FormatColor
.Color = 8711167
.TintAndShade = 0
End With
rng.FormatConditions(1).ColorScaleCriteria(3).Type = _
xlConditionValueHighestValue
With rng.FormatConditions(1).ColorScaleCriteria(3).FormatColor
.Color = 8109667
.TintAndShade = 0
End With
End Sub
Example data:
Code goes in a standard module by pressing Alt + F11 to open VBE and then right click in project and add standard module.

Protect and format specified cells based on change in a cell

I have a cellrange (U4:U50) that allows you to choose between "yes" and "no". I want, for each row, format and protect the cells on the right (V4:AL4, V4:AL4, etc until V50:AL50) when relevant cell in column A changes value.
I am able to put together only a few pieces of the code based on my little knowledge: I managed to make the desired changes happen for the row 4, based on the code below.
The protect and UNprotect sub are in ThisWorkbook and they do exactly that.
Sub Worksheet_Change(ByVal Target As Range)
Set checkRange = Application.Intersect(Target, Range("U4:U50"))
' If the change wasn't in this range then we're done
If checkRange Is Nothing Then Exit Sub
If Range("U4").Value = "Yes" Then
Range("V4:AL4").Select
Call ActiveWorkbook.UNprotect_all_sheets
With Selection
.Locked = True
End With
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark2
.TintAndShade = -9.99786370433668E-02
.PatternTintAndShade = 1
End With
Range("U4").Select
ElseIf Range("U4").Value <> "Yes" Then
Call ActiveWorkbook.UNprotect_all_sheets
Range("V4:AL4").Select
With Selection
.Locked = False
End With
With Selection.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Call ActiveWorkbook.Protect_all_sheets
End Sub
Next step is to make the code work for all the rows depending from the target range, so I started with this
Dim r As Long
Dim c As Long
' 21 targets column U
c = 21
For r = 4 To 50
If Cells(r, c).Value = "Yes" Then
'here I think the process would be to unprotect the sheet, then select from (r,c+1) to (r,c+17), apply the formatting (shade and protection), go to next r and at the end protect the sheet again
But my problem is that I do now know how to:
Select the range of cells from Cells(r,c+1) to Cells(r,c+17);
Make the instruction relative to the right row.
Any comment on that is more than welcome!!
Thanks to all of you in advance, I hope you can understand from my explication what I need to do.
I have been looking for the answer around, maybe I have not been able to look for the right wording..
You can do it this way. Generally there is no need to Select anything but I have left it in as it's not clear whether your other subs are working off a selection. You could use Resize but I can't be bothered to work out how many columns it is from V to AL.
On reflection, it's probably safe to reconfigure the first block as I have done in the second (and perhaps the unprotect should be called before the selecting in any case).
Strictly speaking the code should cater for multiple cells being changed. For this, you can change instances of Target to Target(1).
Sub Worksheet_Change(ByVal Target As Range)
Set checkRange = Application.Intersect(Target, Range("U4:U50"))
' If the change wasn't in this range then we're done
If checkRange Is Nothing Then Exit Sub
If Target.Value = "Yes" Then
Range(Cells(Target.Row, "V"), Cells(Target.Row, "AL")).Select
Call ActiveWorkbook.UNprotect_all_sheets
With Selection
.Locked = True
With .Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark2
.TintAndShade = -9.99786370433668E-02
.PatternTintAndShade = 1
End With
End With
Else
Call ActiveWorkbook.UNprotect_all_sheets
With Range(Cells(Target.Row, "V"), Cells(Target.Row, "AL"))
.Locked = False
With .Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End With
End If
Call ActiveWorkbook.Protect_all_sheets
End Sub

VBA StrComp - Compare values with exceptions

enter image description hereI have today's data in column D which I want to compare with yesterday's data in column F, row wise.
Below is the code I'm using to compare and highlight duplicates.
A) Highlighting blank cells which I don't want.
B) I want to handle some exceptions like I don't wish to highlight $0.00 or specific text "No Data"
Sub CompareAndHighlight()
Dim Myrng1 As Range, Myrng2 As Range, i As Long, j As Long
Application.ScreenUpdating = False
For i = 3 To Sheets("Sheet1").Range("D" & Rows.Count).End(xlUp).Row
Set Myrng1 = Sheets("Sheet1").Range("D" & i)
For j = 3 To Sheets("Sheet1").Range("F" & Rows.Count).End(xlUp).Row
Set Myrng2 = Sheets("Sheet1").Range("F" & j)
If StrComp(Trim(Myrng1.Text), Trim(Myrng2.Text), vbTextCompare) = 0 Then
'If Myrng1.Value = Myrng2.Value Then
Myrng1.Interior.Color = RGB(255, 255, 0)
End If
Set Myrng2 = Nothing
Next j
Set Myrng1 = Nothing
Next i
Application.ScreenUpdating = True
End Sub
Data giving random errors on running macros multiple times after clearing highlighted colors.
Use the conditional formatting function.
Columns("A:A").Select
Selection.FormatConditions.AddUniqueValues
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Selection.FormatConditions(1).DupeUnique = xlDuplicate
With Selection.FormatConditions(1).Font
.Color = -16383844
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13551615
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Then after this create one loop that goes through your range and turns the colour of the cell to no colour where your conditions are met, alternatively you could just filter the data to exclude your cases, such as "No Data", and copy and paste the results into a new column. In fact you do not really need vba for this.
sticking with VBA you could try the following code:
Option Explicit
Sub CompareAndHighlight()
Dim refRng As Range, cell As Range
Application.ScreenUpdating = False
With Worksheets("Sheet1")
Set refRng = .Range("F3", .Cells(.Rows.Count, "F").End(xlUp)).SpecialCells(XlCellType.xlCellTypeConstants)
For Each cell In .Range("D3", .Cells(.Rows.Count, "D").End(xlUp)).SpecialCells(XlCellType.xlCellTypeConstants)
If cell.value <> 0 And cell.value <> "No Data" Then
If refRng.Find(what:=cell.value, LookIn:=xlFormulas, lookat:=xlWhole, MatchCase:=False) Is Nothing Then cell.Interior.color = RGB(255, 255, 0)
End If
Next cell
End With
Application.ScreenUpdating = True
End Sub

Resources