Selection of Active Cell in VBA - vba

I am new to VBA and was learning it via doing exercises, one of the first macros was to color a box red If I click on a macro button. I recorded a macro initially to check whats the VBA code it uses to do that
Sub MakeMeRed()
'
' MakeMeRed Macro
'
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 192
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End Sub
I googled around found that there is another method to select active cell, so I was trying that method to fill the cell.
Sub TestMacro()
'
' TestMacro Macro
'
With ActiveCell
'.Value = "250"
.Color = 200
End With
End Sub
But this code does not work, it does not fill the color of selected cell. Can you point out where I'm going wrong?

Here are 2 ways to refer to the color, inside the cell.
Using the ActiveCell.Interior.ColorIndex and ActiveCell.Interior.Color. ActiveCell.Interior.Color can get 4 different values.
Sub TestMacro()
With ActiveCell
.Value = 1
.Interior.ColorIndex = 3
.Offset(1, 1) = 21
.Offset(1, 1).Interior.Color = RGB(255, 0, 0)
.Offset(1, 2) = 22
.Offset(1, 2).Interior.Color = vbRed 'vbRed = 255
.Offset(1, 3) = 23
.Offset(1, 3).Interior.Color = "&HFF" 'FF = 255; &H is for typeinfo
.Offset(1, 4) = 24
.Offset(1, 4).Interior.Color = 255
End With
End Sub
It looks like this:

To equate the two, ActiveCell in the section is the Selection in the first. To change the color, you'd need to slide in that Interior portion somewhere. You can either have With ActiveCell.Interior or within the with block .Interior.Color = 200.

Related

Deterine a change in cell color from conditional formatting

So my goal is to change the color of any string that has the word "Totals:" in it. Then use logic to Highlight the cells B1 and C1. My current code can change the color but when i use logic it thinks the cells aren't filled.
Sub Macro6()
'
' Macro6 Macro
'
'ActiveWindow.SmallScroll Down:=-12
Range("A1:A381").Select
Selection.FormatConditions.Add Type:=xlTextString, String:="Totals:",
TextOperator:=xlContains
'
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
' With Selection.FormatConditions(1).Font
' .Color = -16383844
' .TintAndShade = 0
' End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13551615 '16777215 '
.TintAndShade = 0
End With
'Selection.FormatConditions(1).StopIfTrue = False
'lastrow = Sheet4.Cells(Sheet4.Rows.Count, "A").End(xlUp).Row
If Sheet1.Cells(9, 1).Interior.Color = 13551615 Then '16777215
MsgBox ("yes")
Else
MsgBox ("wrong")
MsgBox (Sheet4.Cells(6, 1).Interior.Color)
End If
End Sub
You need to use the cell's .DisplayFormat property to retrieve the formatting aspects of a conditional formatting rule.
Option Explicit
Sub Macro1()
With Worksheets("Sheet1")
With .Range("A1:A381")
.FormatConditions.Delete
With .FormatConditions.Add(Type:=xlTextString, String:="Totals:", TextOperator:=xlContains)
.Interior.Color = 13551615 '16777215
.SetFirstPriority
.StopIfTrue = False
End With
End With
End With
With Worksheets("Sheet1")
MsgBox CBool(.Range("A9").DisplayFormat.Interior.Color = 13551615)
End With
End Sub
It may be of worth to note that .DisplayFormat cannot be used within a user defined function (aka UDF).
Thanks for the help! You saved me alot of time. This is what i ended up using encase anyone cares.i ended up noticing the last word was total so i could use the right function
Sub Macro6()
lastrow = Sheet4.Cells(Sheet4.Rows.Count, "A").End(xlUp).Row
Dim A As Integer
For N = 1 To lastrow
A = 1
If Right(Sheet4.Cells(N, 1), 7) = "Totals:" Then
' MsgBox ("Found at" & Sheet4.Cells(N, 1))
'MsgBox (N)
Sheet4.Cells(N, 1).Interior.Color = 13551615
Else
'nothing
' MsgBox ("Found at" & Sheet4.Cells(N, 1))
' MsgBox (N)
End If
'A = A + 1
Next
End Sub

Excel: Hiding cells that are not colored

I have a script that changes the cell color and a script to hide the cells that are not colored. The hide script works, but it hides ALL the cells, even the colored ones. I noticed that when I use the script that changes the cell color, it does not detect the changes in the excel interface(in the 'Fill Color' settings in 'Home' tab, under the 'font size' selection). I also noticed that when try to change the color of the cells (using the excel interface) that are colored from using the script, it does not change (the color seems to be fixed to whatever is set from the script).
Therefore, it seems like the interface does not detect the changes that are being made using the coloring script.
Also, I noticed the script below takes a while to check/hide all the cells. If there is a way to speed up the process, that would be great!
Any help will be greatly appreciated!
Thank you!
The script to hide uncolored cells:
Public Sub HideUncoloredRows()
Dim startColumn As Integer
Dim startRow As Integer
Dim totalRows As Integer
Dim totalColumns As Integer
Dim currentColumn As Integer
Dim currentRow As Integer
Dim shouldHideRow As Integer
startColumn = 1 'column A
startRow = 1 'row 1
totalRows = Sheet1.Cells(Rows.Count, startColumn).End(xlUp).Row
For currentRow = totalRows To startRow Step -1
shouldHideRow = True
totalColumns = Sheet2.Cells(currentRow, Columns.Count).End(xlToLeft).Column
'for each column in the current row, check the cell color
For currentColumn = startColumn To totalColumns
'if any colored cell is found, don't hide the row and move on to next row
If Not Sheet1.Cells(currentRow, currentColumn).Interior.ColorIndex = -4142 Then
shouldHideRow = False
Exit For
End If
Next
If shouldHideRow Then
'drop into here if all cells in a row were white
Sheet2.Cells(currentRow, currentColumn).EntireRow.Hidden = True
End If
Next
End Sub
The script that changes the color certain cells:
Range("A8").Select
Application.CutCopyMode = False
Range("A8").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=COUNTIF(Name_Preps,A8)=1"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Bold = True
.Italic = False
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent3 'Changes the cell to green
.TintAndShade = 0.4
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub
Try to change your condition to follow
For currentColumn = startColumn To totalColumns
'if any colored cell is found, don't hide the row and move on to next row
If Sheet1.Cells(currentRow, currentColumn).Interior.ThemeColor = xlThemeColorAccent3 Then
shouldHideRow = False
Exit For
End If
Next
conditional formatting is not detected by Interior.ColorIndex and the likes
if you want to go on that way you can see here or here for relevant code
but I'd abandon conditional formatting as well as Select/Selection/Activate/ActiveXXX pattern and go simply this way:
Option Explicit
Sub HandleRowsColorAndVisibility()
Dim iRow As Long
With Range("A8", Cells(Rows.count, 1).End(xlUp)) '<--| reference cells from A8 down to column A last not empty cell
ResetRange .Cells '<--| first, bring range formatting and visibility back to a "default" state
For iRow = .Rows.count To 1 Step -1 '<--| then start looping through range
If WorksheetFunction.CountIf(Range("Name_Preps"), .Cells(iRow, 1)) = 1 Then '<-- if current cell matches your criteria ...
FormatRange .Cells(iRow, 1), True, False, 0, xlColorIndexAutomatic, xlThemeColorAccent3, 0.4 '<--| then format it
Else '<--| otherwise...
.Rows(iRow).Hidden = True '<--| hide it!
End If
Next
End With
End Sub
Sub ResetRange(rng As Range)
rng.EntireRow.Hidden = False
FormatRange rng, False, False, 0, xlColorIndexAutomatic, -4142, 0
End Sub
Sub FormatRange(rng As Range, okBold As Boolean, okItalic As Boolean, myFontTintAndShade As Single, myPatternColorIndex As XlColorIndex, myInteriorThemeColor As Variant, myInteriorTintAndShade As Single)
With rng
With .Font
.Bold = okBold
.Italic = okItalic
.TintAndShade = myFontTintAndShade
End With
With .Interior
.PatternColorIndex = myPatternColorIndex
.ThemeColor = myInteriorThemeColor
.TintAndShade = myInteriorTintAndShade
End With
End With
End Sub

How to find a specific cell and replace by a text

On an active range selection, how to find only the cells that contains "0" and "#N/A" - and replace it by text "NA" and change the font color to "red".
Here is the macro I am using to "convert formulas to absolute values " and "to find empty cells to put text "NA".
sub XConvertToValues()
Dim MyRange As Range
Dim MyCell As Range
Set MyRange = Selection
For Each MyCell In MyRange
If MyCell.HasFormula Then
MyCell.Formula = MyCell.Value
End If
If IsEmpty(MyCell.Value) = True Then
MyCell.Value = "NA"
End If
Next MyCell
End Sub
edited after OP's clarification about data format
use Replace() and AutoFilter() method of Range object
Sub XConvertToValues()
With Selection
.Value = .Value '<--| convert all formulas to their values
.Replace What:="#N/A", replacement:="NA", LookAt:=xlWhole
.Replace What:="0", replacement:="NA", LookAt:=xlWhole
If WorksheetFunction.CountIf(.Cells, "NA") > 0 Then
.AutoFilter field:=1, Criteria1:="NA"
.Resize(IIf(.Cells(1) = "NA", .Rows.count, .Rows.count - 1)).Offset(IIf(.Cells(1) = "NA", 0, 1)).SpecialCells(xlCellTypeVisible).Font.ColorIndex = 3
.Parent.AutoFilterMode = False
End If
End With
End Sub
i'm beginner too , this what can i make and maybe it will help you , you can just put number of cells you want to change or rewrite the code with FOR EACH
Dim i As Integer
On Error Resume Next
For i = 1 To 20
cells.Find(What:="0", MatchCase:=False_, SearchFormat:=False).Activate
ActiveCell.FormulaR1C1 = "NA"
With Selection.Font
.Color = -16776961
.TintAndShade = 0
End With
cells.Find(What:="#N/A", MatchCase:=False_, SearchFormat:=False).Activate
ActiveCell.FormulaR1C1 = "NA"
With Selection.Font
.Color = -16776961
.TintAndShade = 0
End With
Next i
edit
Now as you have provided more info, this can be done like:
Try this
Sub ConvertToValues()
Dim R As Long
k = Sheet1.Range("A1048576").End(xlUp).Row '-> total rows in column A
For R = 1 To k
If IsEmpty(Sheet1.Cells(R, 2)) = True Or Sheet1.Cells(R, 2) = "#NA" Or Sheet1.Cells(R, 2) = "0" Then
Sheet1.Cells(R, 2).Value = "NA"
Sheet1.Cells(R, 2).Font.Color = RGB(255, 0, 0)
End If
Next R
End Sub

vba conditional formatting to columns

i am a newbie in VBA, so i come across with several issues.
I have a dataset that looks like this:
I have to compare column A with columns B,C,D,E and F and then color the fonts of the cells in columns B:F under these conditions:
If cells in column A are equal with the cells in columns B:F, paint their font orange.
If cells in column A are higher than the cells in columns B:F, paint their font red.
If cells in column A are lower than the cells in columns B:F, paint their font green.
If the absolute difference between column A and the rest columns (B:F) is less than 1, paint their font orange.
I have tried to write a simple macro and all conditions are met except the 4th.
Here is my attempt.
Sub ConditionalFormating()
Dim i, j, a As Double
a = 0.99
i = 2
j = 2
For j = 1 To 6
For i = 2 To 10
ActiveSheet.Cells(i, j).Select
If ActiveSheet.Cells(i, j) - ActiveSheet.Cells(i, 1) >= a Then
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = RGB(255, 156, 0)
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
If ActiveSheet.Cells(i, j) - ActiveSheet.Cells(i, 1) <= a Then
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = RGB(255, 156, 0)
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
If ActiveSheet.Cells(i, j) > ActiveSheet.Cells(i, 1) Then
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = RGB(0, 255, 0)
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
If ActiveSheet.Cells(i, j) < ActiveSheet.Cells(i, 1) Then
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = RGB(255, 0, 0)
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next
Next
End Sub
Could anyone help me? I cannot understand why the 4th condition is not met when all others are.
Thank you in advance!
To color the font, you have to use the Font property of Range, like: Selection.Font.Color=RGB(255,128,0).
you could try this (commented) code:
Option Explicit
Sub ConditionalFormating()
Dim cell As Range, cell2 As Range, dataRng As Range
Dim colOrange As Long, colRed As Long, colGreen As Long, col As Long
colOrange = RGB(255, 156, 0)
colRed = RGB(255, 0, 0)
colGreen = RGB(0, 255, 0)
With Worksheets("CF") '<--| reference the relevant worksheet (change "CF" to your actual worksheet name)
Set dataRng = Intersect(.Columns("B:F"), .UsedRange)
For Each cell In .Range("A2", .Cells(.Rows.Count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants) '<-- loop through its column "A" not empty cells from row 1 down to last not empty one
If WorksheetFunction.CountA(Intersect(dataRng, cell.EntireRow)) > 0 Then ' if current row has data
For Each cell2 In Intersect(dataRng, cell.EntireRow).SpecialCells(xlCellTypeConstants) ' loop through current column "A" cell row not empty cells
Select Case True '<-- check the current datum against the following conditions
Case cell2.Value = cell.Value Or Abs(cell.Value - cell2.Value) < 1 'if current datum equals corresponding value in column "A" or their absolute difference is lower than 1
col = colOrange
Case cell2.Value < cell.Value 'if current datum is lower then corresponding value in column "A"
col = colRed
Case cell2.Value > cell.Value 'if current datum is higher then corresponding value in column "A"
col = colGreen
End Select
With cell2.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = col
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Next cell2
End If
Next cell
End With
End Sub

Conditional Formatting cells surrounding a given value

So I've set up a conditional formatting VBA macro to highlight two cells: The one with the given string, and the one next to it.
The data set is:
A1 B1
------------------------
PluginID NUM
Host ADDRESS
Severity High
Port PORT
Description DESCRIPTION
Solution SOLUTION
References CVE
The VBA code is:
Sub High2()
'
' High2 Macro
'
'
Columns("A:B").Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=AND($B1=""High"",A1)"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub
This highlights the cell with 'High' in it, and the cell to the left, 'Severity'.
If I change the "=AND($B1=""High"",A1)" line to "=AND($B2=""High"",A1)" then excel will highlight the 2 cells above it in red instead, i.e. Host.
Can anyone help me with highlighting the 4 cells above and 8 cells below the string search-term as well (i.e. the Port, Description, Solution and References cells)?
What you are actual doing if you "change the "=AND($B1=""High"",A1)" line to "=AND($B2=""High"",A1)"" is simply add a new rule. So this will be really the best approach. Adding as much rules as necessary.
Sub High2()
With Columns("A:B").Cells
.Range("A1").Activate
.FormatConditions.Delete
For i = 1 To 3 ' 3 above
.FormatConditions.Add Type:=xlExpression, Formula1:="=($B" & i & "=""High"")"
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
.FormatConditions(1).StopIfTrue = False
Next
For i = 0 To 3 ' 4 below
.FormatConditions.Add Type:=xlExpression, Formula1:="=($B" & .Rows.Count - i & "=""High"")"
.FormatConditions(.FormatConditions.Count).SetFirstPriority
With .FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
End With
.FormatConditions(1).StopIfTrue = False
Next
End With
End Sub
This could also be reached with only one rule:
=OR($B1048573:$B1048576="High", $B1:$B3="High")
But this will lead to bad performance since it is working as an array formula.