alternating row colors/numbers in Excel - VBA - excel

So I am working on a reporting tool in Access. It queries the local tables and creates a Excel document (through VBA) and makes an Excel file.
I use the following code to color alternative code and it works beautifully
For a = 1 To rs.RecordCount
With ExcelSheet
.Cells(a + 1, 1) = a
.Cells(a + 1, 1).EntireRow.Interior.ColorIndex = IIf((a + 1) Mod 2 = 0, 2, 15)
End With
Next
Note I have to do a + 1 because a = 1 is the title row, and that is the title row.
Note: .Cells(a + 1, 1) = 1 numbers the rows (1 , 2, 3, ...)
Note : IIf((a + 1) Mod 2 = 0, 2, 15) The 2 and 15 are color codes.
Now my question is that when someone gets the Excel report they might delete a row, or do a sort operation or whatever and when they do that, it messes up the rows.
ex:
1 white row
2 grey row
3 white row
4 grey row
if i sort them I get
3 white row
1 white row
2 grey row
4 grey row
which is not what I want, I want it to keep the formatting and the numbering
Anyone to accomplish this using VBA in Access?
Tech: Office 2007

This can be accomplished with the ROW() function and some conditional formatting. The ROW() function returns the current row of the cell it is in, so it will change whenever cells are deleted, moved or sorted. Conditional formatting is re-applied whenever its conditions change, so moving or sorting rows would inform Excel to update the colors accordingly. The code would look as follows:
Dim a As Integer
Dim oneRow As Range
For a = 1 To rs.RecordCount
With ExcelSheet
''// show the row number in the first cell
.Cells(a + 1, 1).Formula = "=ROW()"
''// set formatting to alternate row colors
Set oneRow = .Cells(a + 1, 1).EntireRow
oneRow.FormatConditions.Delete
oneRow.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=MOD(ROW()-1, 2)=0"
oneRow.FormatConditions(1).Interior.ColorIndex = 2
oneRow.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=MOD(ROW()-1,2)=1"
oneRow.FormatConditions(2).Interior.ColorIndex = 15
End With
Next a

#e.James
Dim rowRange As Range
ExcelSheet.Cells(1, 1).EntireColumn.ColumnWidth = 4
ExcelSheet.Cells(1, 1) = "#"
Set rowRange = Range("2:2", rs.RecordCount & ":" & rs.RecordCount)
rowRange.Select
With ExcelApp.Selection
.FormatConditions.Delete
.FormatConditions.Add xlExpression, Formula1:="=MOD(ROW(),2)"
.FormatConditions(1).Interior.ColorIndex = 15
End With
That dosnt work. It just highlights the very top row (the title row) grey.
EDIT NEVERMIND
Its supposed to be
Set rowRange = ExcelSheet.Range("2:2", rs.RecordCount & ":" & rs.RecordCount)
EDIT NUMBER 2:
Do you know how I can insert the row numbers in each row using this method?
ANSWER:
ExcelSheet.Cells(1, 1).EntireColumn.ColumnWidth = 4
Set RowRange = Range("2:2", rs.RecordCount & ":" & rs.RecordCount)
RowRange.Columns(1).Formula = "=ROW()-1"
With RowRange
.FormatConditions.Delete
.FormatConditions.Add xlExpression, Formula1:="=MOD(ROW(),2)"
.FormatConditions(1).Interior.ColorIndex = 15
End With

Related

VBA Excel filling up interior color for Entirerow just to the last used column

I am trying to fill up my rows with colour down to the last used column.
I tried:
For i = 2 To lRow
If ActiveSheet.Range("O" & i).Value = "FULL" Then
ActiveSheet.Range ("O" & i), Cells(lCol).Interior.Color = RGB(155, 255, 0)
ElseIf ActiveSheet.Range("O" & i).Value = "NEW" Then
ActiveSheet.Range("O" & i).EntireRow.Interior.ColorIndex = 33
End If
Next
But I am getting "Application defined or object-defined error".
This code is condition-based. When the value "FULL" or "NEW" is to be found down to the last row, then the row with this value has to be highlighted. The problem is, that I don't want to use the entirerow property, as this colour is seen forever. I just need to restrict the .interior.Color property to my last column used.
How can I do that?
I found some other solutions, from where I tried to solve this issue, but in vain.
How to select a range of the second row to the last row
How do I find the last column with data?
First of all, we need to define the lcol properly
Dim wo as Worksheet
Dim lCol as Long
Then always set our worksheet as a priority
Set wo = ThisWorkbook.ActiveSheet
lCol = wo.UsedRange.Columns(wo.UsedRange.Columns.Count - 14).Column
And afterward, define our last column.
I've put -14, which means that the last 14 columns won't be affected, as per the explanation here:
ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?
Next my code should look like this:
For i = 2 To lRow
If ActiveSheet.Range("O" & i).Value = "FULL" Then
ActiveSheet.Range("A" & i).Resize(1, lCol).Interior.Color = RGB(155, 255, 0)
ElseIf ActiveSheet.Range("O" & i).Value = "NEW" Then
ActiveSheet.Range("O" & i).EntireRow.Interior.ColorIndex = 33
End If
Next
referring to the very first column A instead of "O", the filtered value was picked up from.
Another way you can find here:
https://www.thespreadsheetguru.com/blog/2014/7/7/5-different-ways-to-find-the-last-row-or-last-column-using-vba

Change the color of a table rows with a condition

I'm trying to write a VBA in order to change the color (between two different ones) of a table row if the content of a cell is different from the previous.
The row n. 3 must have this color: RGB(221, 245, 253), while the other color is white.
I'm not able to figure out which would be the logic code and how to change the background color of the cells without changing the font color.
Public Sub Overview()
Dim Ovtask As String
Dim Ovn, Ovi As Integer
Ovn = Range("B2").CurrentRegion.Rows.Count
Range("B3:C3").Font.Color = RGB(221, 245, 253)
For Ovi = 3 To Ovn + 1
Ovtask = Range("B" & Ovi)
If Range("B" & Ovi + 1) = Ovtask Then
Range("B" & Ovi + 1 & ":" & "C" & Ovi + 1).Font.Color = Range("B" & Ovi & ":" & "C" & Ovi).Font.Color
Else
Range("B" & Ovi + 1 & ":" & "C" & Ovi + 1).Font.Color = RGB(0, 0, 0)
End If
Next Ovi
End Sub
In the linked image you can see what would be the desired result
As BigBen states in the comments, to set the color of a cell, you use Interior.Color. I thought about conditional formatting, but I think you are right, it's not possible in this case.
The logic you use in your code is flawed: Once it sets a row to white, it will never set any row to blue: Either the next row is equal, then you set it to white because the current row is white, or it is not equal, then you set it to white anyhow.
Have a look to the following code snippet: I declare a boolean variable UseHighlightColor that keeps track if the current row needs to be colored blue or not and sets the Interior.Color accordingly. Some remarks to the color:
- white is RGB(255, 255, 255). RGB(0, 0, 0) results in black.
- there is a predefined constant vbWhite you could use.
- To set the cells transparent instead of white, you can use ColorIndex = xlNone.
And a remark to your code: You are using Range unqualified, so VBA automatically refers to the ActiveSheet (the sheet that has currently the focus). This is not always the sheet you work with. In my example, I have written With ActiveSheet, but you can easily change this so that the code uses the sheet you want, eg ThisWorkbook.Sheets(1). Inside the With, I use the syntax .Range (with leading .), this tells VBA to use the object (sheet) defined in the With-clause. Don't rely on ActiveSheet (and don't use Activate).
With ActiveSheet
Ovn = .Range("B2").CurrentRegion.Rows.Count
Dim useHighLightColor As Boolean
useHighLightColor = True
For Ovi = 3 To Ovn + 1
Dim currentCell As Range
Set currentCell = .Range("B" & Ovi)
If useHighLightColor Then
currentCell.Resize(1, 2).Interior.Color = RGB(221, 245, 253)
Else
' curentCell.Resize(1, 2).Interior.Color = vbWhite
currentCell.Resize(1, 2).Interior.ColorIndex = xlNone
End If
If currentCell <> currentCell.Offset(1, 0) Then
' Switch color
useHighLightColor = Not useHighLightColor
End If
Next Ovi
End With

VBA that will count number of rows until it hits a dark blue cell? (RGB = 93, 123, 157)

Starting in cell B8, I want to count the number of rows down until we hit a cell that is filled with the RGB 93, 123, 157.
I tried using the autofill formula feature while recording, but the cell references stayed absolute: Selection.AutoFill Destination:=ActiveCell.Range("A1:A182")
This will only work if the report has 182 rows, which they won't all have.
I was also given this to try:
Sub Test()
Dim i As Long, bluerow As Long
For i = 1 To 10000
If Cells(i, 2).Interior.Color = RGB(93, 123, 157) Then
bluerow = i
Exit For
End If
Next i
Range("B6").AutoFill Destination:=Range("B6:B" & bluerow), Type:=xlFillDefault
End Sub
But it doesn't put any numbers in column B.
This could work by itself.
Sub NumRws()
'"Cells(5, 2)" is a reference to B5(for some reason, shouldn't it be B8? in that case it should say "Cells(8, 2)")
'"Cells(Rows.Count, 1).End(xlUp)" refers to the last used cell(a cell with any value) in column A
'".Offset(-1, 1)" offsets the second reference to column B and now also one row up("-1,")
'..and "Range(...)" combines the two
'".FormulaR1C1 = "=ROW()-4"" applies the formula which results in row number minus 4(if you change to B8 it should be -7)
Range(Cells(5, 2), Cells(Rows.Count, 1).End(xlUp).Offset(-1, 1)).FormulaR1C1 = "=ROW()-4"
'..Also if you just want the result of the formula do the following instead
With Range(Cells(5, 2), Cells(Rows.Count, 1).End(xlUp).Offset(-1, 1))
.FormulaR1C1 = "=ROW()-4"
.Value = .Value
End With
End Sub
The code below uses Find to get the first cell in column B that matches the color criteria, and then subtracts 7 from the row number.
Sub FindtheFirstColoredCellCountRowsfromRow8()
'Find the first cell in Column(2) with specific interior color and count number of rows
Dim fndCel As Range, cnt As Long
ActiveCell.Interior.Color = RGB(93, 123, 157) 'colors any cell to use in "Find"
Application.FindFormat.Interior.Color = ActiveCell.Interior.Color 'store cell color in find
'set the find range variable to find the first cell that matches the color in Column B
Set fndCel = ActiveSheet.Columns(2).Find("", , , , , xlNext, , , True)
cnt = fndCel.Row - 7 'set the count variable by subtracting 7 from the fndCell row
MsgBox cnt
Application.FindFormat.Clear 'reset FindFormat
ActiveCell.Interior.Color = xlNone 'clear the cell you used to set the color to find
End Sub
Not exactly sure what you're asking for? You want the row number to appear on every cell from B8 till the row where it appears? in that case use:
range("B8:B" & bluerow) = bluerow
This will type the row number where the RGB value is found, starting from B8, down to where the RGB was found. If this is not what you need please explain your problem further.
EDIT: Oh, my bad. Then use this:
For i = 1 To 10000
If Cells(7 + i, 2).Interior.Color = RGB(93, 123, 157) Then
Exit For
Else
Cells(7 + i, 2) = i
End If
Next i
I would suggest finding the last row, though, instead of using "to 10000", you can use:
LastRow = cells(rows.count,2).end(xlup).row

How do I pull text from a cell in a different sheet if the cell two columns away contains specific text?

So essentially what I am trying to do is make name-tags in a spreadsheet for an attendance list I have created in a separate spreadsheet.
I have their full names in one column, and two columns over I have what colour they have been assigned to.
I have separate spreadsheets for each colour for the name-tags.
I want the formula to be written in a separate spreadsheet, let's call it "Green 20". So Green 20 would have multiple cells containing the formula that does the following:
Check to see if the word "Pink" is in a cell between D6:D100 in Spreadsheet
If "Pink" is in the cell, I want the formula to look at the row "Pink" is in and print out cell B? (? meaning whatever row it is) that contains the attendee's name.
So essentially the formula has to get data from a separate spreadsheet, check column D for specific text containing a colour, if the text is in one of the cells in the column then it needs to check the row the text is in and print out the text (First name and last name) in column B corresponding to the row that colour was in.
So I actually went ahead and wrote a macro with one of my co-workers and this is what it ended up looking like:
Public Sub NameTags()
' NameTags Macro
' March 20
Dim Rng As Range
Set Rng = Range("$B$5:$E$100")
Dim rowcount, colselect As Integer
rowcount = 1
colselect = 2
Sheets("March 20, 2017").Range("$B$4:$E$100").AutoFilter Field:=4, Criteria1:="Green"
For Each Row In Rng.Rows
'MsgBox Row.Row
If Cells(Row.Row, 2).EntireRow.Hidden = False Then
If Cells(Row.Row, 2).Value <> "" Then
copystring = Cells(Row.Row, 2).Value & " " & Cells(Row.Row, 3).Value
Sheets("Green 20").Cells(rowcount, colselect) = copystring
Sheets("Green 20").Activate
Cells(rowcount, colselect).Select
Set mergecellrng = Cells(rowcount, colselect)
Set mergecellrng2 = mergecellrng.Offset(0, 3)
Range(mergecellrng, mergecellrng2).Merge
mergecellrng.Font.Name = "Segoe UI"
mergecellrng.Font.Size = 22
mergecellrng.HorizontalAlignment = xlCenter
mergecellrng.VerticalAlignment = xlCenter
If colselect = 8 Then
rowcount = rowcount + 7
End If
Select Case colselect
Case 2
colselect = 8
Case 8
colselect = 2
End Select
End If
End If
Sheets("March 20, 2017").Activate
Next
An it repeats for each colour

Copying specific coloured cells onto a different worksheet

I'm working on a spreadsheet with conditional formatting, which turns some cells green and some red, depending on if they are in/out of the correct range.
What I need is for the red "out of spec" numbers to be copied onto the next sheet leaving the green "within spec" number off the second sheet. A bit like this:
Sheet 1:
a 2
b 4
c 5
d 6
e 3
Sheet 2:
a
b 4
c 5
d 6
e
I hope this makes sense, I did take screenshots but I can't post them! My fingers are crossed that someone can help :)
Thank you in advance
Jazz
I have assumed that data is in Column A of Sheet1.
Tested
Sub checkColornCopy()
Find the last row for automation
lastRow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
sheet2Counter = 1
For i = 1 To lastRow
Extracting the color of the Cell interior
ConditionalColor = Worksheets("Sheet1").Cells(i, 1).Interior.ColorIndex
Color Index 3 denotes "Red"
If ConditionalColor = 3 Then
If the color is Red thenCopying the cell content of Sheet1 to Sheet2
Worksheets("Sheet2").Cells(sheet2Counter, 1).Value = Worksheets("Sheet1").Cells(i, 1).Value
Making the cell content of Sheet1 blank
Worksheets("Sheet1").Cells(i, 1).Value = " "
sheet2Counter = sheet2Counter + 1
End If
Next
End Sub
This is probably not the best way to do it but, it worked for me.
Try:
Dim i As Integer
Dim cell As String
Sheets("Sheet1").Activate
For i = 1 To 10
'Check if font is red
If Range("A" & i).Font.Color = "fontcolor" Then
cell = Range("A" & i).Value
'Check for a number in the cell and remove the right most number
While IsNumeric(Right(cell, 1))
cell = Range("A" & i).Value
cell = Left(cell, Len(cell) - 1)
Sheets("sheet2").Range("A" & i).Value = cell
Wend
Else
'If font is not red then display cell value on sheet2
Sheets("sheet2").Range("A" & i).Value = Sheets("sheet1").Range("A" & i).Value
End If
Next
Sheets("Sheet2").Activate
Edited
In this case "A3" has red font.
To find the color of your red font use:
sub Text_Color()
Dim color As String
'"A3" has red text.
color = Sheets("sheet1").Range("A3").Font.color
MsgBox "My text color is= " & color
End Sub
Take the number found in the msgbox, in this example 393372. And replace "fontcolor" from the above code with 393372 .

Resources