答案 0 :(得分:0)
合并单元格的简单VBA代码
Sub merg_exp_1()
ActiveSheet.Range("A1:C10").Merge
End Sub
现在让我们看看,如果我们合并一行会发生什么。此示例代码 虽然一般的运动只针对一种情况进行测试 如下:
Sub Merge_Rows()
Dim rng As Range
Dim rrow As Range
Dim rCL As Range
Dim out As String
Dim dlmt As String
dlmt = ","
Set rng = ActiveSheet.Range("A1:C5")
For Each rrow In rng.Rows
out = ""
For Each rCL In rrow.Cells
If rCL.Value <> "" Then
out = out & rCL.Value & dlmt
End If
Next rCL
Application.DisplayAlerts = False
rrow.Merge
Application.DisplayAlerts = True
If Len(rrow.Cells(1).Value) > 0 Then
rrow.Cells(1).Value = Left(out, Len(out) - 1)
End If
Next rrow
End Sub
显示运行程序之前和之后的示例数据。你可以看到这不符合你的目标。
接下来我们可以尝试按列方法合并。我们也在这里尝试 对于一列,即B列,以查看效果。示例代码为 如下:
Sub Merge_col_exp()
Dim cnum As Integer
Dim rng As Range
Dim str As String
For i = ActiveSheet.UsedRange.Rows.Count To 1 Step -1
cnum = Cells(i, 1).MergeArea.Count
Set rng = Range(Cells(i, 2), Cells(i - cnum + 1, 2)) ' only to demonstrate working in 2nd column
For Each cl In rng
If Not IsEmpty(cl) Then str = str + "," + cl
Next
If str <> "" Then str = Right(str, Len(str) - 1)
Application.DisplayAlerts = False
rng.Merge
rng = str
Application.DisplayAlerts = True
str = ""
i = i - cnum + 1
Next i
End Sub
显示运行程序之前和之后的样本数据。您可以看到这更接近您的要求。您可以通过在Actively used范围中查找Last Column来扩展此程序的功能。扩展程序功能以涵盖最后一栏。