2009-12-18 27 views
0

我有VBA代碼來選擇同一行上的單元格範圍,然後合併該選擇的左對齊。在Excel中合併並左對齊行範圍

我想對其進行增強以允許我選擇範圍或行塊並對範圍中的每一行執行相同的操作。

回答

0

下面是做這件事:

  1. 通過an auxiliary function獲取在工作表中的最後一行人口。

  2. 遍歷行,併爲每一行找到通過另一個輔助函數使用的最後一列。

  3. 將生成的動態創建的選擇合併並左對齊。

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 
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 
0

爲什麼不使用Merge Across?它是合併下拉下的內置工具。如果你需要調整Merge的工作方式,你也可以使用.Merge(Across)