gpt4 book ai didi

excel - 基于列值合并单元格的 VBA 宏

转载 作者:行者123 更新时间:2023-12-04 21:29:36 25 4
gpt4 key购买 nike

我正在尝试使用基于列值的 VBA 合并 excel 中的单元格。例如,在第一行,只要月份相同,就合并这些单元格。我试过以下代码:

Sub Main()

Dim j As Long

For j = 1 To 13
If StrComp(Cells(1, j), Cells(1, j + 1), vbTextCompare) Then
Range(Cells(1, j), Cells(1, j + 1)).Merge
End If

Next j

End Sub

在这里,我将行固定为第一行并遍历列并检查下一个单元格值是否与当前值相同。但是,在输出中它合并了不正确的单元格。我在这里想念什么?

enter image description here

最佳答案

这更容易理解。

Application.DisplayAlerts = False
With ThisWorkbook.Sheets("Sheet1")
For i = 13 To 2 Step -1 'Loop from the last cell, and stop at the second column
If .Cells(1, i).Value = .Cells(1, i).Offset(, -1).Value Then
.Range(.Cells(1, i), .Cells(1, i).Offset(, -1)).Merge
End If
Next i
End With
Application.DisplayAlerts = True

关于excel - 基于列值合并单元格的 VBA 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57606788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com