PDA

View Full Version : [SOLVED:] VBA Conditional formatting - multiple adjacent cells if specific text on left



Terrific
02-13-2020, 01:27 PM
If a cell contains "z" then highlight the 3 cells to the right of it. Example If C4=z then C4, D4, E4, F4 turn yellow. J5=z then J5, K5, L5, M5 turn yellow. For my application I need to use VBA not regular conditional formatting.

p45cal
02-15-2020, 09:04 AM
A really lazy (=inefficient) way:
Sub blah()
For Each cll In ActiveSheet.UsedRange
If cll.Value = "z" Then cll.Resize(, 4).Interior.Color = vbYellow
Next cll
End Sub

Terrific
02-17-2020, 07:21 AM
Thanks for the reply. I tried this and nothing happened plugged it in.

p45cal
02-17-2020, 08:14 AM
plugged it in.What does this mean?


You have to run it.
Otherwise attach a workbook.

Terrific
02-17-2020, 09:10 AM
Attached is the file with what you sent, but isn't working. Let me know what I might be missing.

p45cal
02-17-2020, 09:21 AM
Delete the Option Explicit line.

Terrific
02-17-2020, 09:43 AM
That's how I first put it in and it didn't work. I deleted Option Explicit again, but it still isn't working. Not sure what I'm doing wrong.

Paul_Hossler
02-17-2020, 10:17 AM
Put this in the worksheet code module




Option Explicit


Private Sub Worksheet_Change(ByVal Target As Range)
Dim r As Range

On Error GoTo NiceExit
For Each r In Target.SpecialCells(xlCellTypeConstants, xlTextValues).Cells
If r.Value = "z" Then r.Resize(1, 4).Interior.Color = vbYellow
Next


NiceExit:
End Sub

p45cal
02-17-2020, 10:24 AM
Nor am I.
Trying to add a vid…
https://app.box.com/s/r8ptkxzpk5iqocxc28h9z3u8bqaz8yo3

ok just a link then:
https://app.box.com/s/r8ptkxzpk5iqocxc28h9z3u8bqaz8yo3

Paul_Hossler
02-17-2020, 10:36 AM
That's how I first put it in and it didn't work. I deleted Option Explicit again, but it still isn't working. Not sure what I'm doing wrong.


If you don't want to use a WS change event, then I'd put it in a standard module, not the WS code module




Option Explicit


Sub blah()
Dim cll As Range

On Error GoTo NiceExit
For Each cll In ActiveSheet.UsedRange.SpecialCells(xlCellTypeConstants, xlTextValues).Cells
If cll.Value = "z" Then cll.Resize(, 4).Interior.Color = vbYellow
Next cll

NiceExit:
End Sub

Terrific
02-17-2020, 12:03 PM
Thanks very much Paul. That did the trick