如果整行中的值相同,我想合并列中的单元格。
例如。如果A1:G1的范围与A2:G2相同,则我要合并A1:A2单元格,即B1:B2到G1:G2。
在下面的代码中,我得到运行时错误13:类型不匹配。我假设,问题在于检查两个范围的相等性。
Dim i As Long, j As Long, row as Long
row = Cells(Rows.Count, 6).End(xlUp).row
For i = row To 7 Step -1
If Range(Cells(i, 7), Cells(i, 24)).Value = Range(Cells(i - 1, 7), Cells(i - 1, 24)).Value Then
For j = 7 To 24 Step 1
Range(Cells(i, j), Cells(i - 1, j)).Merge
Next j
End If
Next i
问题是,如何检查两个范围值是否相等?
在评论后编辑: 使用下面的代码,它实际上可以工作
Dim i As Long, j As Long, row As Long
row = Cells(Rows.Count, 6).End(xlUp).row
For i = row To 7 Step -1
If Join(Application.Transpose(Application.Transpose(Range(Cells(i, 7), Cells(i, 24)))), Chr(0)) = Join(Application.Transpose(Application.Transpose(Range(Cells(i - 1, 7), Cells(i - 1, 24)))), Chr(0)) Then
For j = 7 To 24 Step 1
Range(Cells(i, j), Cells(i - 1, j)).Merge
Application.DisplayAlerts = False
Next j
End If
Next i
但是,我想知道为什么您(@Pᴇʜ)将函数分隔为第一行和最后一行。
此外,使用我的代码,在不合并单元格的情况下,我可以使用te循环更改单元格颜色:
Dim row As Long
row = Cells(Rows.Count, 6).End(xlUp).ro
Do Until IsEmpty(Cells(row, 3))
If row Mod 2 <> 0 Then
Range(Cells(row, 3), Cells(row, 24)).Interior.Color = RGB(217, 225, 242)
Else
Range(Cells(row, 3), Cells(row, 24)).Interior.Color = xlNone
End If
row = row + 1
Loop
合并单元格后如何处理?
答案 0 :(得分:2)
问题是……
Range(Cells(i, 7), Cells(i, 24)).Value
返回一个值数组,但是不能将一个值数组与=
比较。因此,您需要遍历所有这些值,并将每个值与
Range(Cells(i - 1, 7), Cells(i - 1, 24)).Value
由于您已经具有此循环,只需将If
语句移至循环中即可进行检查:
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
请注意,我将变量命名更改为更有意义的名称。这也避免了将Row
用作变量名,而变量名是Excel本身使用的代名词。
根据评论进行编辑
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
将打开以下内容
进入
答案 1 :(得分:2)
如果范围具有多个单元格,则范围的value
属性将返回一个数组。您可以比较循环中每个元素的值,也可以使用join()
将数组转换为字符串,然后进行比较(请参阅this answer)。