CodexBloom - Programming Q&A Platform

Excel VBA to Automatically Highlight Rows Based on Cell Value - working with Inconsistent Behavior

đź‘€ Views: 1968 đź’¬ Answers: 1 đź“… Created: 2025-06-16
excel vba automation

I'm trying to implement I'm prototyping a solution and I tried several approaches but none seem to work. I'm trying to create a macro in Excel VBA that automatically highlights entire rows based on the value of a specific cell in that row. My goal is to highlight rows where the value in column C is greater than 100. However, I'm experiencing inconsistent behavior—sometimes rows are highlighted correctly, and other times they are not. Here’s the code snippet I’m using: ```vba Sub HighlightRowsBasedOnValue() Dim ws As Worksheet Set ws = ThisWorkbook.Sheets("Sheet1") Dim lastRow As Long lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row Dim i As Long For i = 2 To lastRow If ws.Cells(i, "C").Value > 100 Then ws.Rows(i).Interior.Color = RGB(255, 255, 0) ' Yellow Else ws.Rows(i).Interior.ColorIndex = xlNone End If Next i End Sub ``` I’ve tested the macro on a dataset of around 500 rows, and while it works as expected most of the time, there are scenarios where it fails to highlight rows even though the condition is met. I also noticed that if I manually change the value in column C after running the macro, the highlighting does not update unless I run the macro again. I’ve tried adding `Application.Calculate` before my loop to force Excel to recalculate, but it didn’t resolve the scenario. I suspect it could be related to how Excel handles calculations or maybe the way I'm referencing cells. Is there a better approach to ensure that the highlighting is consistent? Any help would be greatly appreciated! For context: I'm using Vba on Linux. Could someone point me to the right documentation? I'm developing on Ubuntu 22.04 with Vba. Is there a simpler solution I'm overlooking?