在Excel中合并和左对齐一系列行

时间:2009-12-18 21:01:42

标签: excel vba merge range

我有VBA代码来选择同一行上的一系列单元格然后合并&左对齐那个选择。

我想增强它以允许我选择范围或行块,并对范围中的每一行执行相同的操作。

3 个答案:

答案 0 :(得分:0)

这是一种方法:

  1. 通过an auxiliary function获取工作表中最后填充的行。

  2. 迭代行,并为每一行找到通过另一个辅助函数使用的最后一列。

  3. 合并生成的动态创建的选择并左对齐。

  4. Important note from Microsoft:只有一个范围的左上角单元格中的数据(范围:工作表上的两个或更多个单元格。一个范围内的单元格可以相邻或不相邻。)所选单元格中的数据将保留在合并的单元格。将删除所选范围的其他单元格中的数据。

    Option Explicit
    
    Sub merge_left_justify()
        Dim i As Long
        Dim j As Long
    
        Dim last_row As Long
        Dim last_col As Long
    
        last_row = find_last_row(ThisWorkbook.ActiveSheet)
    
        Application.DisplayAlerts = False
    
        For i = 1 To last_row Step 1
            j = find_last_col(ThisWorkbook.ActiveSheet, i)
            Range(Cells(i, 1), Cells(i, j)).Select
            Selection.Merge
            Selection.HorizontalAlignment = xlLeft
        Next i
    
        Application.DisplayAlerts = True
    End Sub
    
    Function find_last_row(ByRef ws As Worksheet)
        Dim last_row
        last_row = Cells.Find(what:="*", after:=[a1], _
            searchorder:=xlByRows, searchdirection:=xlPrevious).row
        find_last_row = last_row
    End Function
    
    Function find_last_col(ByRef ws As Worksheet, ByVal row As Long)
        Dim last_col
        last_col = Cells(row, 255).End(xlToLeft).Column
        find_last_col = last_col
    End Function
    

答案 1 :(得分:0)

实际上,为了回答我自己的问题,我在寻找帮助的同时玩了一些代码并想出了这个。有人看到任何问题吗?似乎工作,除了我仍然有一个IF语句的问题,该语句应该忽略并且不合并任何空白行,所以它只是在这里注释掉了。

Sub MergeLeft()

    Dim range As range
    Dim i As Integer
    Dim RowCount As Integer

    ' Merge Macro
    ' Keyboard Shortcut: Ctrl+Shift+A

    RowCount = Selection.Rows.Count
    For i = 1 To RowCount
       Set range = Selection.Rows(i)
       'If range(i) <> "" Then
       With range
          .HorizontalAlignment = xlLeft
          .VerticalAlignment = xlBottom
          .WrapText = False
          .Orientation = 0
          .AddIndent = False
          .IndentLevel = 0
          .ShrinkToFit = False
          .ReadingOrder = xlContext
          .MergeCells = False
       End With
       range.Merge
       'End If
    Next i

End Sub

答案 2 :(得分:0)

为什么不使用Merge Across?它是合并下拉列表下的内置工具。如果你需要调整Merge的工作方式,你也可以使用.Merge(Across)