简体   繁体   English

VBA宏基于列值合并单元格

[英]VBA Macro to Merge Cells based on Column Values

I'm trying to merge cells in excel using VBA based on the column value. 我正在尝试基于列值使用VBA合并excel中的单元格。 For instance, on row one, wherever the month is the same, merge those cells. 例如,在第一行,无论月份如何,都将这些单元格合并。 I've tried the following code : 我尝试了以下代码:

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

Here, I'm keeping the row fixed as the first row and iterating over the columns and checking if the next cell value is same as the current value. 在这里,我将行固定为第一行,并在各列上进行迭代,并检查下一个单元格值是否与当前值相同。 However, in the output it's merging incorrect cells. 但是,在输出中它合并了不正确的单元格。 What am I missing here? 我在这里想念什么?

在此处输入图片说明

Should work like this … 应该像这样工作...

Option Explicit

Public Sub MergeSameValuesInRow()
    Const iRow As Long = 1         'the row number
    Const FirstColumn As Long = 1  'first column with data in iRow

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1")  'define your worksheet

    Dim LastColumn As Long  'find last used column in iRow
    LastColumn = ws.Cells(iRow, ws.Columns.Count).End(xlToLeft).Column

    Dim StartCell As Range  'remember the start cell (first occurence of a new value)
    Set StartCell = ws.Cells(iRow, FirstColumn)

    Dim iCol As Long
    For iCol = FirstColumn + 1 To LastColumn + 1  'loop through columns in iRow
        If ws.Cells(iRow, iCol).Value <> StartCell.Value Then  'if value changed …
            Application.DisplayAlerts = False  'hide merging messages
            ws.Range(StartCell, ws.Cells(iRow, iCol - 1)).Merge  'merge from start cell until one before value change
            Application.DisplayAlerts = True

            Set StartCell = ws.Cells(iRow, iCol)  'set start cell to the next value
        End If
    Next iCol
End Sub

It will change this … 它将改变这个……
在此处输入图片说明

into this … 进入这个……
在此处输入图片说明

This is easier to understand. 这更容易理解。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM