excel - 使用 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 行 + 迭代次数作为行参考点。
解决方案
- 确定最后一行
- 循环遍历合并的每一行(从 69 开始)
D to I
- 循环完成后,一次格式化整个范围
这还会检查以确保您的最后一行确实大于 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
推荐阅读
- c# - 在 ASP.NET Core 标识中只允许数字密码
- python - 如何安装 requirements.txt 并忽略未找到的模型
- java - Android sqlite数据库在更新查询时没有这样的列
- javascript - 移除水平滚动条并使表格更宽
- elasticsearch - ELK logstash 无法在 ES 中创建索引
- jenkins - 在 Jenkins 管道中超时后重试 - 解决方法
- javascript - 动态选择 React 组件并将数据应用为 props
- google-maps - Google Maps API - 折线作为图像
- python - 在 Matplotlib 中自定义轴
- javascript - napi 中的字符串返回限制