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:
VBA: วิธีนับจำนวนคอลัมน์ที่ใช้
VBA: วิธีเปลี่ยนความสูงของแถว
VBA: วิธีเปลี่ยนความกว้างของคอลัมน์