Change font in a cell based on a value - vba

I am trying to change the font in a range of cells depending on the value of these cells. So, I'd like to change the font of D1 depending on D1's value, and I'd like to change the font of D2 depending on D2's value, and so on up to D33.
I was able to find results for how to change the font of A CELL depending on the value of another cell here. This VBA code did the job for D1 only. However, it did not work for D2, D3, D4 and so on.
Could someone help me adjust that code to my need?
I apologize if this question is so easy to answer, but I'm not familiar with how VBA coding works.

This code will do what you've described, in this case applying a font to the text in column C based upon the special characters you mention in column D (Notice that I'm using 1 rather than "1", etc...). If Column D doesn't contain any of those characters, it assumes the desired font name is in column D -- I did this just to provide a test of the code. Of course, you'll need to modify the code for your particular situation, but hopefully this gets you started.
Option Explicit
Sub fontChange()
Dim theRange As Range, cell As Range
Set theRange = Range("C1:C16")
For Each cell In theRange
Select Case cell.Offset(0, 1)
Case 0, 1, "(":
cell.Font.Name = "Wingdings 2"
Case "", ":":
cell.Font.Name = "Wingdings"
Case Else:
cell.Font.Name = cell.Offset(0, 1)
End Select
Next
End Sub
In the animated gif I step through the code so you can see it working.

Related

Change cell color based on another cell value

In a workbook I have, the D column has a formula in it to derive the last six digits of a value in column C. These columns are located in a sheet titled "JE". I have a dynamic SQL connected query that has values in the A column. That query is located in a sheet titled "required_refs". I essentially, want to write: If the value in the D column cell matches/equals any of the values in that query in sheet "required_refs", turn the F column cell red in sheet JE.
Example: If cell D10 has a value that equals any of the values in column A in "required_refs", turn cell F10 red. In addition, if cell D13 has a value that matches/equals a value in column A in sheet "required_refs", turn F13 red. And so on.
Here is the code I tried. I added it in Sheet "JE":
Code:
Sub ChangeCellColor()
Dim ref_code As Range: Set ref_code = Range("D7:D446").Value
Dim refCode_Confirm As Range: Set refCode_Confirm = Worksheets("required_refs").Range("A:A").Value
Dim colorChange As Range: Set colorChange = Worksheets("required_refs").Range("A:A")
For Each cell In ref_code
If cell.Value = refCode_Confirm.Value Then
Range("F7:F446").ActiveCell.Interior.ColorIndex = 3
Next cell
End If
End Sub
Currently, this code just doesn't do anything. It doesn't turn the F column cell red. I've asked a question similar to this but, the workbook I'm using has changed a bunch since then, and this question is a bit more simple than the previous one.
If anyone could help, I'd really appreciate it. Thanks!
Your code has a number of issues.
.Value returns a basic type, like a string or long. You can't assign this to a range variable.
Your End If and Next cell statements are swapped around. Always use correct indentation so these errors become more obvious.
You have an undeclared variable cell. This can potentially cause bugs. In the VBE, turn on the Tools > Options > Editor > Required Variable Declaration option to force the use of Option Explicit in new modules.
Fixing these issues leads us to this:
Sub ChangeCellColor()
Dim cell As Range
Dim ref_code As Range: Set ref_code = Range("D7:D446")
Dim refCode_Confirm As Range: Set refCode_Confirm = Worksheets("required_refs").Range("A:A")
Dim colorChange As Range: Set colorChange = Worksheets("required_refs").Range("A:A")
For Each cell In ref_code
If cell.Value = refCode_Confirm.Value Then
Range("F7:F446").ActiveCell.Interior.ColorIndex = 3
End If
Next cell
End Sub
Unfortunately, it still doesn't work as you can't compare a single value directly against a column of values in VBA.
This following code corrects this remaining issue. Note the choosing of good meaningful names as well as the use of RVBA for the variables. This is a good tip for how to avoid making similar errors. Also note the use of .Value2 instead of .Value. This is highly recommended.
Sub ChangeCellColor()
Dim rngRef As Range
Dim rngRefsToCheck As Range: Set rngRefsToCheck = Range("D7:D446")
Dim rngRequiredRefs As Range: Set rngRequiredRefs = Worksheets("required_refs").Columns("A")
Dim rngColorChangeRequired As Range: Set rngColorChangeRequired = Columns("F")
For Each rngRef In rngRefsToCheck
If Not IsError(Application.Match(rngRef.Value2, rngRequiredRefs, 0)) Then
rngColorChangeRequired.Cells(rngRef.Row).Interior.ColorIndex = 3
End If
Next rngRef
End Sub
The best and fastest way to achieve the color change would be to use Advanced Filters, thus avoiding the need to loop. However, since you're still learning the basics, I've shown the looping version.

Conditional Formatting or Macro Enabled - Change cell background color based on another cell value

I have a workstation inventory list that has a purchase date in cell "D" in which I have cell "I2" with =TODAY(). Cell "E" has a formula of =ROUND(YEARFRAC(D3,$I$2),0) to get the # of years value in Cell "E".
My question is regarding cell "F" I'd like for the cell to automatically change color based on the numbers of years in cell "E", but I'm struggling to do so. With either conditional formatting or finding a good macro to do so.
I have attached a screenshot to give you folks a better idea. I might've missed a similar thread while doing my research, but if anyone knows where I could look. That's a good answer for me.
You can use the regular conditional formatting:
Select "Use a formula to determine which cells to format" , set the rule like in the screen-shot below (if Years >= 1 and Years <=3).
Apply this formula to your entire range (don't forget to remove the $ sign before the row number so it will change with the rows numbers).
Repeat this step by adding 2 more rules for the other scenarios (same type by using a formula):
(if Years > 3 and Years <=4) then Yellow.
(if Years > 5) then Red. In your post you wrote: (Years > 5) in your legend in the right, but in your requested screen-shot you actually want to display if (Years >= 5) then Red. so you need to decide which one you want.
Select ColumnF and HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::
=AND(ROW()>2,E1>4,E1<>"")
Format..., select red Fill, OK, OK.
Then add a new rule of:
=AND(ROW()>2,E1<5,E1<>"")
with yellow fill and finally a third rule (though you could choose to apply a 'standard' fill instead) of:
=AND(ROW()>2,E1<4,E1<>"")
with the rather strange colour fill.
[1] If not added in the above order they should be rearranged in the Conditional Formatting Rules Manager window with red at the bottom and yellow in the middle.
[2] Check Stop if True for all three rules (or at least the top two).
[3] 0 is covered within the same rule as 1 to 3 years.
[4] To simplify range selection and updating all rules apply to the entire column. This though has complicated avoiding applying the formatting to the first two rows and any that are blank in ColumnE.
Try below conditions, it worked for me. You need to apply three different rules on same range
=$K$5>=5 - Red
=AND($K$5<5,$K$5>3) -Yellow
=AND($K$5>=1,$K$5<=3) - Green
I tend to limit conditional formatting to cases where I use them for a quite small and FIXED (never to be changed/added/deleted/moved) number of cells
Otherwise in the medium/long run it can both result in a worksheet mess (after copying&pasting and/or inserting/deleting cells) and size increase
That's why for the colouring of cells down a list I'd always use a VBA approach, like the following code:
Option Explicit
Public Sub main()
Dim cell As Range
Dim firstColor As Long, secondColor As Long, thirdColor As Long
With Worksheets("Inventory") '<--| change "Inventory" to your actual sheet name
firstColor = .Range("I9").Interior.Color '<--| change "I9" to your actual cell address with "1st color"
secondColor = .Range("I10").Interior.Color '<--| change "I10" to your actual cell address with "2nd color"
thirdColor = .Range("I11").Interior.Color '<--| change "I11" to your actual cell address with "3rd color"
For Each cell In .Range("E3", .Cells(.Rows.Count, "E").End(xlUp)).SpecialCells(XlCellType.xlCellTypeFormulas, xlNumbers) '<--| loop through column "E" from row 3 down to last non empty row cells with numbers deriving from formulas only
cell.Offset(, 1).Interior.Color = Switch(cell.value <= 3, firstColor, cell.value <= 4, secondColor, cell.value > 4, thirdColor) '<--| adjust current cell adjacent one color according to current cell value
Next cell
End With
End Sub
Note: I adjusted Switch() function conditions to match your example column "E" and "F" result, which is slightly different from what would come out of your "NO. Of Years" range legenda. Also, this latter has its first two ranges overlapping each other

Selecting every Nth row, Excel. Replace with nothing or original cell content

I've got an Excel sheet with my variables listed in column E and their values listed in column G
I would like to test if E contains the word "text" (my variable). If so then I want to replace the corresponding cell in column G with "This is my successful if statement text".
If not -- I want the cell to either be left alone (impossible in excel) or keep the value it originally had (I think the issue is its populated with text not numbers).
So far ive tried
=if(e2="text", "Replace with this", G2)
as well as
=if(e2="text", "replace with this", "")
The top returns a number while the bottom returns an empty cell which deletes the contents I had there.
Any suggestions? I think this can be done with VB but that's out of my league.
The proper way to solve this is as so.
In column H (or any that doesn't contain any information) place the formula
=IF(E2 = "text", "This is the true part", G2) and drag down.
This will test E2 for the word "text" and then replace with "this is true.." If the conditions are not met, the original text from G2 is pulled into the new column.
Once this is complete, the desired results should have taken effect. You can then copy the row and use "Paste Special" and select "Values" from the pop up menu to paste in your new data. Selecting Values allows the user to paste the actual field data, not the formula that generated it!
Try this.
Sub g()
Dim ws As Worksheet
Dim lastRow As Long
Set ws = ThisWorkbook.Worksheets("Sheet1") 'change sheet name as applicable
lastRow = ws.Cells(ws.Rows.Count, "E").End(xlUp).Row
For i = 1 To lastRow
With ws
If .Cells(i, 5) = "text" Then
.Cells(i, 7) = "The text you want"
End If
End With
Next
End Sub
It seems like you are trying to get four values from column E that you want to parse (cut up) and place in Column G.
By creating four parses { =mid(e2,16,10), =mid(e3, 9, 15), =mid(e4,5,3), =mid(e5,10,22) } in cells G2, G3, G4, and G5, respectively, you can select the block of four G cells (G2:G5), select the block at the bottom right, and drag it down throughout the file.
Optionally, you can use modulo math and case statements to loop through the file and perform the required function at each point:
myCount = 0
myLoop = 0
endMyLoop = false
range("G2").activate
do
myLoop = myCount mod 4
select case myLoop
case 0
code for description_tag
case 1
code for title_tag
case 2
code for headline
case 3
code for text
end select
if activecell.value = "" then endMyLoop = true
loop until (endMyLoop = true)
You stated that every fourth row the value in E is text. So, it should just be a matter of copying the formula every fourth row or performing your function every fourth iteration (modulo returns the remainder) in the G column.
One other option would be to nest your if loops (=if(e2="text","Its text",if(e2="title_tag","Its a title",if(e2="headline","Its headline","Its description")))) to account for the four different options. Of course you would fill the text with the function that you actually want to perform.

Highlight cells + adjacent 2 cells if certain text if located

If any cell contains the text "example", this cell + the two cells on the same row to the right of, to be highlighted.
So for instance
B5 contains "example", b5,c5,d5 need to be highlighted orange
b9 contains "example", b9,c9,d9 need to be highlighted orange.
And so forth across the whole sheet. Multiple rows and multiple columns could contain the specific text.
Any assistance, examples appreciated.
Private Sub CommandButton1_Click()
row_number = 4
Do
DoEvents
row_number = row_number + 1
swing_data = Sheet1.Range("B" & row_number)
If InStr(swing_data, "Test") >= 1 Then
With Range("B" & row_number).Offset(, 2).Interior
.Pattern = x1solid
.PatternColorIndex = x1automatic
.Color = 65535
.PatternTintAndShade = 0
End With
End If
Loop Until swing_data = ""
End Sub
This is not highlighting the 2 cells to the right, and if there is a blank cell it's stopping. Also it's only working on one column. Needs to work on columns B, E, N, Q, Z, AC,
Changed this line
<<code>With Range("B" & row_number).Offset(, 2).Interiorcode>
To read <code>With Range("B" & row_number).resize(, 3).Interiorcode>
And it works.
Would the be an easier way to include multiple columns in this...?
Conditional formatting:
As multiple columns may contain your criteria you need a bit more complex formula (conditional formatting - use a formula...): =or(iferror(rc[-1]="example",false),iferror(rc[-2]="example",false),rc="example") - notes: I switch to R1C1 reference style before entering conditional formatting as I find it mite clear there; iferror is necessary to make formula working also in first and second columns.
VBA:
you can use VBA find object to cycle through all instances and change formatting there (I think built-in help and maybe recording some short macros give you enough information to create it)
You can do this with conditional formatting if you want to avoid VBA. Select the cells you want you want to apply the formatting to (say B1:D10), Click conditional formatting -> New Rule... -> Use a formula to determine which cells to format. Use this formula
=EXACT($B1,"example")
The $ in front of the column makes sure only that column is looked at, the row will be independent. You then need to change the formatting to whatever you want. In your case change the fill to orange.

How to count up text of a different font colour in excel

I have a list of names that has been exported from another database into excel. The names in the list that are of interest are highlighted in red font. I would like a way to count it, i.e. John Smith appears 5 times in total in a column but 3 of the 5 times, his name comes up highlighted in red font. So I would like to see how many instances of his name comes up red.
I know How to search all instances of his name e.g. =COUNTIF(A1:A100,"John Smith ")
I've also had help in creating a VB function which counts all values that are red (=SumRed) (once the colour index is specified) in a worksheet by using this:
Function SumRed(MyRange As Range)
SumRed = 0
For Each cell In MyRange
If cell.Font.Color = 255 Then
SumRed = SumRed + cell.Value
End If
Next cell
End Function
I just can't find a way to combine the two counting conditions. Any help would be much appreciated!
You don't need VBA for this but still if you want VBA Solution then you can go with any of the other two answers. :)
We can use Excel formula to find the Font Color of a cell. See this example.
We will be using XL4 macros.
Open the Name Manager
Give a name. Say FontColor
Type this formula in Refers To =GET.CELL(24,OFFSET(INDIRECT("RC",FALSE),0,-1)) and click OK
Explanation of the formula
The Syntax is
GET.CELL(type_num, reference)
Type_num is a number that specifies what type of cell information you want.
reference is the cell reference
In the above formula the number 24 gives you the font color of the first character in the cell, as a number in the range 1 to 56. If font color is automatic, returns 0. And Hence the drawback. Ensure that the entire font color is red. We could have used 64 but that is not working properly.
OFFSET(INDIRECT("RC",FALSE),0,-1) refers to the immediate cell on the left.
Now enter this formula in a cell =IF(AND(Fontcolor=3,B1="John Smith"),1,0) and copy it down.
Note: The formula has to be entered on the Right of the cell which contains the Text.
Screentshot
EDIT (10/12/2013)
To count cells with specific backcolor see THIS link
I think you're almost there but this deserves another function #user bet me to the punch line :(
Function CoundRedAndText(MyRange As Range, Mytext as string) as long
CoundRedAndText = 0
For Each cell In MyRange
If cell.Font.Color = 255 and cell.value like MyText Then
CoundRedAndText = CoundRedAndText + 1 'you had cell.value but dont know why?
End If
Next cell
End Function
Usage, =CountRedAndText(A1:A25, "John Smith")
For Each cell In Range("A1:A100")
If cell.Font.Color = 255 And cell.Value = "John Smith" Then
myCount = myCount + 1
End If
Next