首页 > 解决方案 > 使用 VBA 按变量值动态合并和居中单元格

问题描述

我正在尝试x使用带有 VBA 的静态起点合并和居中单元格数量。

我的起点将永远是Cell D69,我将始终D - I从第 69 行开始将列合并在一起,然后将文本向左对齐。

我当前的宏看起来像这样:

Range("D69:I69").Select
        With Selection
            .HorizontalAlignment = xlCenter
            .VerticalAlignment = xlBottom
            .Orientation = 0
            .AddIndent = False
            .IndentLevel = 0
            .ShrinkToFit = False
            .ReadingOrder = xlContext
            .MergeCells = False
        End With
        Selection.merge
        With Selection
            .HorizontalAlignment = xlLeft
            .VerticalAlignment = xlBottom
            .WrapText = False
            .Orientation = 0
            .AddIndent = False
            .IndentLevel = 0
            .ShrinkToFit = False
            .ReadingOrder = xlContext
            .MergeCells = True
        End With

我需要对第 69 行之后的行继续这个过程x。我在尝试实现一个x用作我的迭代次数的循环时遇到了困难,并且起点是第 69 行 + 迭代次数作为行参考点。

标签: excelvba

解决方案


  1. 确定最后一行
  2. 循环遍历合并的每一行(从 69 开始)D to I
  3. 循环完成后,一次格式化整个范围

这还会检查以确保您的最后一行确实大于 69,否则会出错。


Option Explicit

Sub Merge_For_Client()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1") '<-- Update Sheet
Dim LR As Long, i As Long

LR = ws.Range("D" & ws.Rows.Count).End(xlUp).Row

Application.ScreenUpdating = False
Application.DisplayAlerts = False
    If LR >= 69 Then

        For i = 69 To LR
            ws.Range(ws.Cells(i, "D"), ws.Cells(i, "I")).Merge
        Next i

        With ws.Range(ws.Cells(69, "D"), ws.Cells(LR, "I"))
            .HorizontalAlignment = xlLeft
            'Add any other formats you want to apply in this With Block
        End With

    End If
Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

推荐阅读