Vba:如何合并具有相同值的单元格
您可以在VBA中使用以下语法来合并特定范围内具有相同值的单元格:
Sub MergeSameCells()
'turn off display alerts while merging
Application.DisplayAlerts = False
'specify range of cells for merging
Set myRange = Range(" A1:C13 ")
'merge all same cells in range
MergeSame:
For Each cell In myRange
If cell.Value = cell.Offset(1, 0).Value And Not IsEmpty(cell) Then
Range(cell, cell.Offset(1, 0)).Merge
cell.VerticalAlignment = xlCenter
GoTo MergeSame
End If
Next
'turn display alerts back on
Application.DisplayAlerts = True
End Sub
这个特定的宏合并A1:C13范围内具有相同值的单元格。
以下示例展示了如何在实践中使用此语法。
示例:在VBA中合并具有相同值的单元格
假设我们在 Excel 中有以下数据集,其中包含有关各个篮球运动员得分的信息:
假设我们要合并连续行中具有相同值的单元格。
我们可以创建以下宏来执行此操作:
Sub MergeSameCells()
'turn off display alerts while merging
Application.DisplayAlerts = False
'specify range of cells for merging
Set myRange = Range(" A1:C13 ")
'merge all same cells in range
MergeSame:
For Each cell In myRange
If cell.Value = cell.Offset(1, 0).Value And Not IsEmpty(cell) Then
Range(cell, cell.Offset(1, 0)).Merge
cell.VerticalAlignment = xlCenter
GoTo MergeSame
End If
Next
'turn display alerts back on
Application.DisplayAlerts = True
End Sub
当我们运行这个宏时,我们会收到以下输出:
请注意,包含相同会议名称和团队名称的每个单元格均已合并。
请注意,我们使用cell.VerticalAlignment = xlCenter语句来指定文本应在合并单元格中垂直居中。
其他资源
以下教程说明如何在 VBA 中执行其他常见任务: