How to check if two ranges value is equal

大憨熊 提交于 2019-12-02 08:33:26

The issue is that …

Range(Cells(i, 7), Cells(i, 24)).Value

returns an array of values, but you cannot compare an array of values with =. Therefore you need to loop throug all these values and compare each value with the corresponding value in

Range(Cells(i - 1, 7), Cells(i - 1, 24)).Value

Since you already have this loop just move your If statement to check this into the loop:

Dim iRow As Long, iCol As Long, LastRow as Long
LastRow = Cells(Rows.Count, 6).End(xlUp).row
For iRow = LastRow To 7 Step -1
    For iCol = 7 To 24 Step 1
        If Cells(iRow, iCol).Value = Cells(iRow - 1, iCol).Value Then
            Range(Cells(iRow, iCol), Cells(iRow - 1, iCol)).Merge
        End If
    Next iCol 
Next iRow 

Note that I changed the variable naming to more meaningful names. This also avoids using Row as variable name which is alerady used by Excel itself.


Edit according comments

Option Explicit

Sub Test()
    Dim RangeToMerge As Range
    Set RangeToMerge = Range("C5:F14")

    Dim FirstMergeRow As Long
    FirstMergeRow = 1

    Dim iRow As Long, iCol As Long
    For iRow = 1 To RangeToMerge.Rows.Count - 1
        If Join(Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Transpose(RangeToMerge.Rows(FirstMergeRow).Value)), "|") <> _
           Join(Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Transpose(RangeToMerge.Rows(iRow + 1).Value)), "|") Then
            If iRow <> FirstMergeRow Then
                For iCol = 1 To RangeToMerge.Columns.Count
                    Application.DisplayAlerts = False
                    RangeToMerge.Cells(FirstMergeRow, iCol).Resize(rowsize:=iRow - FirstMergeRow + 1).Merge
                    Application.DisplayAlerts = True
                Next iCol
            End If
            FirstMergeRow = iRow + 1
        End If
    Next iRow

    'merge last ones
    If iRow <> FirstMergeRow Then
        For iCol = 1 To RangeToMerge.Columns.Count
            Application.DisplayAlerts = False
            RangeToMerge.Cells(FirstMergeRow, iCol).Resize(rowsize:=iRow - FirstMergeRow + 1).Merge
            Application.DisplayAlerts = True
        Next iCol
    End If
End Sub

Will turn the following

into

The value property of a range returns an array if the range has more than one cell. You can either compare the values of each element in a loop, or you can use join() to convert the arrays to strings and then compare those (see this answer).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!