Hi, my sheet has 103 columns and 18550 rows of data which is coming from database. Based on B column cells value i have to apply formatting for the respective row like [if B2 value is 1 then for that row interior color should be Orange in color else if it is -1 then it should be in Blue else if it is 0 then the columns F & G should be Green in color and these green coloured cells should not be locked. And every 1 valued row and the immediate -1 valued rows should be grouped. Currently i have the following code which is almost taking 8 minutes of time to apply formattings.
With ThisWorkBook.Sheets("RoAe").Range("A1:A" & rowLen)
'=================For 1 valued Rows==========
Set C = .Find("1", LookIn:=xlValues)
x=0
If Not C Is Nothing Then
firstAddress = C.Address
Do
valR = Split(C.Address, "$")
actVal = valR(2)
ReDim Preserve HArray(x)
HArray(x) = actVal + 1
x = x + 1
With ThisWorkBook.Sheets("RoAe").Range("D" & actVal & ":FN" & actVal)
.Rows.AutoFit
.WrapText = True
.Font.Bold = True
.Interior.Color = RGB(252,213,180)
.Borders.Color = RGB(0, 0, 0)
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
End With
Set C = .FindNext(C)
Loop While Not C Is Nothing And C.Address <> firstAddress
End If
'=================For -1 valued Rows==========
Set C = .Find("-1", LookIn:=xlValues)
y=0
If Not C Is Nothing Then
firstAddress = C.Address
Do
valR = Split(C.Address, "$")
actVal = valR(2)
ReDim Preserve HArray(y)
FArray(y) = actVal + 1
y = y + 1
With ThisWorkBook.Sheets("RoAe").Range("D" & actVal & ":FN" & actVal)
.Rows.AutoFit
.WrapText = True
.Font.Bold = True
.Interior.Color = RGB(141,180,226)
.Borders.Color = RGB(0, 0, 0)
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
End With
Set C = .FindNext(C)
Loop While Not C Is Nothing And C.Address <> firstAddress
End If
'===================For 0(Zero) Valued Rows============
For p = 0 To UBound(HArray)
groupRange = "A" & HArray(p) & ":A" & FArray(p)
For i = 0 To UBound(arrUnlockMonthStart)
unlockRange = F & (HArray(p) + 1) & ":" & G & FArray(p)
ThisWorkBook.Sheets("RoAe").Range(unlockRange).Locked = False
ThisWorkBook.Sheets("RoAe").Range(unlockRange).Interior.Color = RGB(216,228,188)
Next
next
end with
ThisWorkBook.Sheets("RoAe").protect "12345"
Can we do the same with Conditional Formatting. Applying format & locking/unlocking for the rows based on cell value. Any help would be appreciated greatly.
As i mentioned that you cannot lock/unlock a cell in conditional formatting. You will have to first apply the conditional formatting and then lock/unlock the cells. Also you do not need to loop to apply conditional formatting. You can do that in one go.
Try this
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long, i As Long
Dim Rng As Range, unlockRng As Range
'~~> Set this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find the last row in Col B
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
'~~> Set your range where CF will be applied for -1/1
Set Rng = .Range("D2:H" & lRow)
With Rng
.FormatConditions.Add Type:=xlExpression, Formula1:="=$B2=1"
.FormatConditions(1).SetFirstPriority
With .FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = 0.399945066682943 '<~~ Orange
End With
.FormatConditions(1).StopIfTrue = True
.FormatConditions.Add Type:=xlExpression, Formula1:="=$B2=-1"
.FormatConditions(2).SetFirstPriority
With .FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorLight2
.TintAndShade = 0.599993896298105 '<~~ Blue
End With
.FormatConditions(1).StopIfTrue = True
End With
'~~> Set your range where CF will be applied for 0
Set Rng = .Range("F2:G" & lRow)
With Rng
.FormatConditions.Add Type:=xlExpression, Formula1:="=$B2=0"
.FormatConditions(3).SetFirstPriority
With .FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent3
.TintAndShade = 0.399975585192419 '<~~ Green
End With
.FormatConditions(1).StopIfTrue = True
End With
'~~> Loop through cells in Col B to checl for 0 and store
'~~> relevant Col F and G in a range
For i = 2 To lRow
If .Range("B" & i).Value = 0 Then
If unlockRng Is Nothing Then
Set unlockRng = .Range("F" & i & ":G" & i)
Else
Set unlockRng = Union(unlockRng, .Range("F" & i & ":G" & i))
End If
End If
Next i
End With
'~~> unlock the range in one go
If Not unlockRng Is Nothing Then unlockRng.Locked = False
End Sub
ScreenShot
EDIT
For 103 Columns and 18550 Rows use this method. This is much faster than the above
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long, i As Long
Dim Rng As Range, unlockRng As Range
'~~> Set this to the relevant worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Application.ScreenUpdating = False
With ws
'~~> Find the last row in Col B
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
'~~> Set your range where CF will be applied for -1/1
'~~> Taking 103 Columns into account
Set Rng = .Range("D2:DB" & lRow)
With Rng
.Locked = True
.FormatConditions.Delete
.FormatConditions.Add Type:=xlExpression, Formula1:="=$B2=1"
.FormatConditions(1).SetFirstPriority
With .FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent6
.TintAndShade = 0.399945066682943 '<~~ Orange
End With
.FormatConditions(1).StopIfTrue = True
.FormatConditions.Add Type:=xlExpression, Formula1:="=$B2=-1"
.FormatConditions(2).SetFirstPriority
With .FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorLight2
.TintAndShade = 0.599993896298105 '<~~ Blue
End With
.FormatConditions(1).StopIfTrue = True
End With
'~~> Set your range where CF will be applied for 0
Set Rng = .Range("F2:G" & lRow)
With Rng
.FormatConditions.Add Type:=xlExpression, Formula1:="=$B2=0"
.FormatConditions(3).SetFirstPriority
With .FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent3
.TintAndShade = 0.399975585192419 '<~~ Green
End With
.FormatConditions(1).StopIfTrue = True
End With
'~~> Loop through cells in Col B to check for 0 and
'~~> unlock the relevant range
For i = 2 To lRow
If .Range("B" & i).Value = 0 Then
.Range("F" & i & ":G" & i).Locked = False
End If
Next i
End With
Application.ScreenUpdating = True
End Sub
As far as I know, the locking and grouping cannot be done with Conditional Formatting, the coloring however can be done.
You can color a cell based o a formula entered in conditional formatting dialog and this formula can contain relative, semi-relative and absolute references to other cells (using the $ notation as in any other formulas).
For example the "make row orange if column B = 1" can be done by setting condition formatting in cell D2 to formula =if($B1=1;TRUE;FALSE). If you put the $ in front of B as in this example, than you can apply the conditional formatting to the whole range columns D:H and it should color the lines as your script does.
Doing all the colors is just repeating the process and setting more conditional formating rules with different formulas.
Related
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
This macro is supposed to find the value NULL in column "W" and paint the row it found NULL on in a color. It does that fine however if I try to search for a number in the same column(that i know exists there) it doesn't seem to find the value. Any help would be appreciated.
Sub e()
MsgBox "some question?", , "Marvin The Paranoid Android"
Dim fNameAndPath As Variant, wb As Workbook
Dim LastRow As Long, i As Long, sht As Worksheet
Dim myValue As Variant
fNameAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.XLSX), *.XLSX", Title:="Èçáåðåòå ôàéë ñ èìå /Ðåâîëâèíãè/")
If fNameAndPath = False Then Exit Sub
Set wb = Workbooks.Open(fNameAndPath)
Set sht = wb.Worksheets("Sheet1")
X = wb.Name
Windows(X).Activate
'Macro optimization
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
'000000000
ActiveWindow.Zoom = 85
Rows("1:1").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("A1:W1").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Range("A:E,L:N").EntireColumn.AutoFit
Columns("F:F").ColumnWidth = 6.14
Columns("G:G").ColumnWidth = 6.43
Columns("H:K").ColumnWidth = 5.43
Range("O:R,T:V").ColumnWidth = 4.71
Columns("S:S").ColumnWidth = 14.71
Rows("1:1").RowHeight = 54.54
Range("A1").Select
myValue = InputBox("Give me some input")
LastRow = sht.Cells(sht.Rows.Count, "W").End(xlUp).row
For r = 1 To LastRow
If Cells(r, Columns("W").Column).Value = myValue Then
Rows(r).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next r
Range("A1").Select
Application.Calculation = xlCalculationAutomatic
wb.Close SaveChanges:=True 'or false
'Reverse macro optimization
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "Îáðàáîòèõ ôàéë /Ðåâîëâèíãè/...", , "Marvin The Paranoid Android"
End Sub
Autofilter() method of Range object can detect "23" both as number and a text:
With sht
With .Range("W1", .Cells(.Rows.Count, "W").End(xlUp)) '<--| consider column "W" values down to its last non empty row
.AutoFilter field:=1, Criteria1:=myValue '<--| filter column "W" on 'myValue'
If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then '<--| if any values match...
With .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Interior '<--|... consider only filtered values, and apply formatting
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
End With
.ShowAllData '<--| show all rows back...
End With
Try replacing your For loop with the piece of code below.
If you are using Decimal values, or values larger than Integer, make the changes from CInt to your needs:
For r = 1 To LastRow
If sht.Cells(r, "W").Value = CInt(myValue) Then
sht.Rows(r).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next r
Try replacing your loop with this:
Dim tempFind
Set tempFind = ActiveSheet.Columns("W").Find(What:=myValue, LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
If Not tempFind Is Nothing Then
With Range(tempFind.Address).Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Else
MsgBox "Not Found!"
End If
When you say:-
if I try to search for a number in the same column(that i know exists there) it doesn't seem to find the value
I assuming you are referring to the below line from your code not returning true and running the code within the If statement.
If Cells(r, Columns("W").Column).Value = myValue Then
In short, if its not finding a match then there is not a match, but it can be hard to see sometimes.
Examples of not matching when you think it should are:-
If the cell contains 12.12121212 but is formatted to show it as 12.12, if you search for 12.12 (as you think that would match) it will not match.
If the cell contains leading or trailing spaces, '12.12 ' (space at the end), if you search for 12.12 (no space at the end) it will not match.
We can see what you are trying to match or what you think should be a match from your question but the above should be the information needed to work the answer out from your content.
Based on the comments, try altering your code with the below, I've added some debugging lines to help understand why its failing: -
'If the value is null it will skip trying to check it, this mean no type mismatch error
If Not IsNull(Cells(r, Columns("W").Column).Value) then
'This prints the value in the cell, the searched value, and if its seen as a match
Debug.Print "'" & Cells(r, Columns("W").Column).Value & "' ,'" & myValue & "', " & (Cells(r, Columns("W").Column).Value = myValue)
'Compares them both as Long data types
If CLng(Cells(r, Columns("W").Column).Value) = CLng(myValue) Then
'Your code
End If
End If
I've been trying to add the entire row that meets the highlight criteria to an array but I've been struggling getting it to work.
The code loops through multiple identifiers and highlight them in red based off of the preconditions. I would like to add the entire row to an array for all rows meeting the precondition criteria.
Sub SWAPS101()
'red color
' If "Security Type" = SW
' If "New Position Ind" = N
' If "Prior Price" = 100
' If "Current Price" does not equal 100
Dim rng As Range, lCount As Long, LastRow As Long
Dim cell As Object
'Sheets("Output").Activate
With ActiveSheet
LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
For Each cell In .Range("E2:E" & LastRow) 'new position
If cell = "N" And cell.Offset(, 16) = "SW" And cell.Offset(, 5) = 100 _
And cell.Offset(, 4) <> 100 Then
With cell.EntireRow.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 6382079
.TintAndShade = 0
.PatternTintAndShade = 0
End With
' LastRow = Range("b65000").End(xlUp).Row
' For r = 2 To LastRow
Row = Row + 1
TempArray(Row, 1) = Cells(r, cell))
Next r
End If
Next cell
End With
End Sub
Using the Range.CurrentRegion property to isolate the 'island' of data radiating out from A1 is an easy method to restrict the 'scope' of the operation. You do not want to be copying thousands of blank cells into an array.
Sub SWAPS101()
'red color
' If "Security Type" = SW
' If "New Position Ind" = N
' If "Prior Price" = 100
' If "Current Price" does not equal 100
Dim a As Long, r As Long, c As Long, vVALs As Variant
With Sheets("Output")
'reset the environment
If .AutoFilterMode Then .AutoFilterMode = False
.Columns(5).Interior.Pattern = xlNone
With .Cells(1, 1).CurrentRegion
ReDim vVALs(1 To .Columns.Count, 1 To 1)
.AutoFilter field:=Application.Match("security type", .Rows(1), 0), Criteria1:="SW"
.AutoFilter field:=Application.Match("new position ind", .Rows(1), 0), Criteria1:="N"
.AutoFilter field:=Application.Match("prior price", .Rows(1), 0), Criteria1:=100
.AutoFilter field:=Application.Match("current price", .Rows(1), 0), Criteria1:="<>" & 100
With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
'check to ensure that there is something to work with
If CBool(Application.Subtotal(103, .Cells)) Then
With Intersect(.Columns(5), .SpecialCells(xlCellTypeVisible))
.Cells.Interior.Color = vbRed
End With
Debug.Print .SpecialCells(xlCellTypeVisible).Areas.Count
With .SpecialCells(xlCellTypeVisible)
For a = 1 To .Areas.Count
Debug.Print .Areas(a).Rows.Count
For r = 1 To .Areas(a).Rows.Count
Debug.Print .Areas(a).Rows(r).Address(0, 0)
ReDim Preserve vVALs(1 To UBound(vVALs, 1), 1 To UBound(vVALs, 2) + 1)
For c = 1 To .Columns.Count
vVALs(c, UBound(vVALs, 2)) = _
.Areas(a).Rows(r).Cells(1, c).Value
Next c
Next r
Next a
vVALs = Application.Transpose(vVALs)
End With
'array is populated - do something with it
Debug.Print LBound(vVALs, 1) & ":" & UBound(vVALs, 1)
Debug.Print LBound(vVALs, 2) & ":" & UBound(vVALs, 2)
'this dumps the values starting a couple of rows down
With .Cells(.Rows.Count, 1).Offset(3, 0)
.Resize(UBound(vVALs, 1), UBound(vVALs, 2)) = vVALs
End With
End If
End With
End With
If .AutoFilterMode Then .AutoFilterMode = False
End With
End Sub
I've left a lot of the debug.print statements in so you can watch how the process loops through the rows of each Range.Areas property within the Range.SpecialCells method's xlCellTypeVisible set. Use F8 to step through the code while keeping an eye on the VBE's Immediate window ([Ctrl]+G).
Post-processing results
You can add ranges to an array, such as:
Dim myArray() As Variant 'declare an unallocated array.
myArray = Range("E2:E" & LastRow) 'myArray is now an allocated array, range being your row
My idea is to create union range uRng but I couldn't fill it in array so create temp sheet and past this range in it then fill the selection (the copied range) in array then delete this temp sheet.
this will work but I don't know if it is good way so this is just an idea because Jeeped answer seems the full answer for this question
Sub SWAPS101()
'red color
' If "Security Type" = SW
' If "New Position Ind" = N
' If "Prior Price" = 100
' If "Current Price" does not equal 100
Dim rng As Range, lCount As Long, LastRow As Long
Dim cell As Range
Dim TempArray As Variant, uRng As Range, tempSH As Worksheet
'Sheets("Output").Activate
With ActiveSheet
LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
For Each cell In .Range("E2:E" & LastRow) 'new position
If cell = "N" And cell.Offset(, 16) = "SW" And cell.Offset(, 5) = 100 _
And cell.Offset(, 4) <> 100 Then
With cell.EntireRow.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 6382079
.TintAndShade = 0
.PatternTintAndShade = 0
End With
If uRng Is Nothing Then
Set uRng = cell.EntireRow
Else
Set uRng = Union(uRng, cell.EntireRow)
End If
End If
Next cell
End With
If Not uRng Is Nothing Then
Application.ScreenUpdating = False
Set tempSH = Sheets.Add
uRng.Copy
tempSH.Paste
TempArray = Selection.Value
Application.DisplayAlerts = False
tempSH.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End If
End Sub
I think I have an issue with the order of my For IF and Next statements, I am trying to only highlight the row where all conditions are meet, instead when my code makes it to the highlighting part all rows are individually highlighted and the code seems to run quite slow, I believe I am performing too many iterations?
Sub SWAPS100()
Dim rng As Range, lCount As Long, LastRow As Long
Dim cell As Object
Sheets("Output").Activate
With ActiveSheet
LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
For Each cell In .Range("E2:E" & LastRow) 'new position
If cell = "N" Then
Debug.Print
For Each cell1 In .Range("U2:U" & LastRow) 'Secuirty type
If cell1 = "SW" Then
For Each cell2 In .Range("J2:J" & LastRow) 'prior px
If cell2 = 100 Then
For Each cell3 In .Range("I2:I" & LastRow) 'current px
If cell3 <> 100 Then
'With cell.Interior
With cell.EntireRow.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 6382079
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next cell3
End If
Next cell2
End If
Next cell1
End If
Next cell
End With
As #Raystafarian commented as I was typing, use And in your if statment instead of all the loops:
Sub SWAPS100()
Dim rng As Range, lCount As Long, LastRow As Long
Dim cell As Object
Sheets("Output").Activate
With ActiveSheet
LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
For Each cell In .Range("E2:E" & LastRow) 'new position
If cell = "N" And cell.Offset(, 16) = "SW" And cell.Offset(, 5) = 100 _
And cell.Offset(, 4) = 100 Then
With cell.EntireRow.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 6382079
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next cell
End With
With looping each row individually it will go slow and will most likely always justify. As long as you have one cell in each column that justifies the if statement then it will color all rows.
Also this can be done with Conditional Formatting with the following formula:
=AND($E2="N",$U2="SW",$J2=100,$I2=100)
While the aforementioned Conditional Formatting with a native worksheet formula is a better solution for 'on-the-fly' updates, a series of AutoFilter methods applied to the columns would be much faster than any procedure involving looping through the cells.
Sub SWAPS100()
Application.ScreenUpdating = False
With Sheets("Output")
If .AutoFilterMode Then .AutoFilterMode = False
With .Cells(1, 1).CurrentRegion
.AutoFilter Field:=5, Criteria1:="N"
.AutoFilter Field:=9, Criteria1:=100
.AutoFilter Field:=10, Criteria1:=100
.AutoFilter Field:=21, Criteria1:="SW"
With .Resize(.Rows.Count - 1, 1).Offset(1, 4)
If CBool(Application.Subtotal(103, .Cells)) Then
.Cells.EntireRow.Interior.Color = 6382079
End If
End With
End With
If .AutoFilterMode Then .AutoFilterMode = False
End With
Application.ScreenUpdating = True
End Sub
I am trying to code this procedure to highlight all rows of which have a value of "N" in their respective row within Column N
I am not too familiar with coding VBA formatting and I cannot get this procedure to function
Sub highlight_new_pos()
Dim rng As Range, lCount As Long, LastRow As Long
Dim cell As Object
With ActiveSheet 'set this worksheet properly!
LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
For Each cell In .Range("N2:N" & LastRow)
If cell = "N" Then
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Next cell
End With
End Sub
Option Explicit
Sub highlight_new_pos()
Dim cel As Object
With ActiveSheet
For Each cel In .Range("N2:N" & .Cells(.Rows.Count, 14).End(xlUp).Row)
If UCase(cel.Value2) = "N" Then cel.Interior.Color = 65535
Next
End With
End Sub
This will be faster if you have a lot of rows:
Sub highlight_new_pos1()
Application.ScreenUpdating = False
With ActiveSheet
With .Range("N1:N" & .Cells(.Rows.Count, 14).End(xlUp).Row)
.AutoFilter Field:=1, Criteria1:="N"
.Offset(1, 0).Resize(.Rows.Count - 14, .Columns.Count).Interior.Color = 65535
.AutoFilter
End With
End With
Application.ScreenUpdating = True
End Sub
In your code, you are looping through the cells, but you're still changing the color of the initial selection (not of the cell in the loop). Adjust as follows:
Sub highlight_new_pos()
Dim rng As Range, lCount As Long, LastRow As Long
Dim cell As Object
With ActiveSheet 'set this worksheet properly!
LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
For Each cell In .Range("N2:N" & LastRow)
If cell = "N" Then
With cell.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End if
Next cell
End With
End Sub
If you want the entire row, change cell.Interior to cell.entirerow.Interior