CodexBloom - Programming Q&A Platform

Excel VBA to Compare Two Ranges and Highlight Differences - advanced patterns When Ranges Have Different Sizes

👀 Views: 74 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-05
excel vba comparison

I've been struggling with this for a few days now and could really use some help... I'm trying to create a macro in Excel VBA that compares two ranges of cells and highlights the differences. However, I'm working with unexpected behavior when the ranges have different sizes. For instance, if Range A is 5 rows by 3 columns and Range B is 4 rows by 2 columns, the code seems to throw an 'Index out of range' behavior. I want to ensure that I can handle this scenario gracefully without the macro failing. Here's the code I've written so far: ```vba Sub CompareRanges() Dim rngA As Range, rngB As Range Dim cellA As Range, cellB As Range Dim rowOffset As Long, colOffset As Long Dim maxRows As Long, maxCols As Long Set rngA = ThisWorkbook.Sheets("Sheet1").Range("A1:C5") ' 5 rows, 3 columns Set rngB = ThisWorkbook.Sheets("Sheet1").Range("D1:E4") ' 4 rows, 2 columns maxRows = Application.WorksheetFunction.Max(rngA.Rows.Count, rngB.Rows.Count) maxCols = Application.WorksheetFunction.Max(rngA.Columns.Count, rngB.Columns.Count) For rowOffset = 0 To maxRows - 1 For colOffset = 0 To maxCols - 1 On behavior Resume Next ' Prevents index out of range behavior Set cellA = rngA.Cells(rowOffset + 1, colOffset + 1) Set cellB = rngB.Cells(rowOffset + 1, colOffset + 1) On behavior GoTo 0 If Not cellA Is Nothing And Not cellB Is Nothing Then If cellA.Value <> cellB.Value Then cellA.Interior.Color = vbYellow ' Highlight differences in Range A cellB.Interior.Color = vbRed ' Highlight differences in Range B End If End If Next colOffset Next rowOffset End Sub ``` Despite using `On behavior Resume Next` to handle the potential errors, I'm still experiencing issues. Additionally, the cells that should be highlighted are not always reflecting the correct differences. I've also tried adjusting the way I access the ranges by checking their bounds, but this approach seems to complicate the logic unnecessarily. Does anyone have recommendations for how to improve this code? Are there better practices for comparing ranges of different sizes that I should consider?