Sub MergeCells_top() Dim Today As Date Dim ColNum As Integer Dim StartCell As Range Dim EndCell As Range Dim MergeRange As Range '获取今日日期所在的列号 Today = Date ColNum = Application.Match(Today, Range("7:7"), 0) '计算需要合并的单元格范围 Set StartCell = Range("C3") Set EndCell = Cells(4, ColNum) Do While Not IsEmpty(EndCell) And EndCell.Row < Rows.Count Set EndCell = EndCell.Offset(1, 0) Loop Set EndCell = EndCell.Offset(-1, 0) '合并单元格并设置为居中对齐 Set MergeRange = Range(StartCell, EndCell) MergeRange.Merge MergeRange.HorizontalAlignment = xlCenter End Sub我想在这段代码中再添加一个功能,使C371也实现合并居中,判断依据和C3相同 调整完之后提示格式已调整
时间: 2024-02-14 20:17:35 浏览: 138
好的,根据您的要求,可以将代码稍作修改,实现将 C3 和 C371 合并并居中,以下是修改后的代码:
```
Sub MergeCells_top()
Dim Today As Date
Dim ColNum As Integer
Dim StartCell As Range
Dim EndCell As Range
Dim MergeRange As Range
Dim EndCell1 As Range
'获取今日日期所在的列号
Today = Date
ColNum = Application.Match(Today, Range("7:7"), 0)
'计算需要合并的单元格范围
Set StartCell = Range("C3")
Set EndCell = Cells(4, ColNum)
Do While Not IsEmpty(EndCell) And EndCell.Row < Rows.Count
Set EndCell = EndCell.Offset(1, 0)
Loop
Set EndCell = EndCell.Offset(-1, 0)
'计算需要合并的单元格范围
Set EndCell1 = Cells(371, ColNum)
Do While Not IsEmpty(EndCell1) And EndCell1.Row > 1
Set EndCell1 = EndCell1.Offset(-1, 0)
Loop
Set EndCell1 = EndCell1.Offset(1, 0)
'合并单元格并设置为居中对齐
Set MergeRange = Range(StartCell, EndCell)
Set MergeRange1 = Range("C371", EndCell1)
MergeRange.Merge
MergeRange1.Merge
MergeRange.HorizontalAlignment = xlCenter
MergeRange1.HorizontalAlignment = xlCenter
'提示格式已调整
MsgBox "格式已调整!"
End Sub
```
您只需要将这段代码复制到 VBA 编辑器中即可,然后运行 `MergeCells_top` 这个宏即可实现合并 C3 和 C371 并居中对齐,同时会弹出一个提示框提示格式已调整。请注意,这段代码中假设今日日期所在行为第 7 行,如果您的情况不同,需要将代码中的 `Range("7:7")` 改为对应的行号。
阅读全文