gpt4 book ai didi

VBA用循环合并单元格

转载 作者:行者123 更新时间:2023-12-03 02:33:15 28 4
gpt4 key购买 nike

我想合并 A 列和 B 列中的两个单元格,例如如下所示,只要我有记录,下面是我的代码,但不起作用,并且不合并单元格,不知道问题出在哪里。谢谢

.Range("A5", "A6").Merge
.Range("A7", "A8").Merge
.Range("A9", "A10").Merge

.Range("B5", "B6").Merge
.Range("B7", "B8").Merge
.Range("B9", "B10").Merge


Dim i As Integer
Dim j As Integer
Dim xlMerge As Range
Dim xlMergeJ As Range

For i = 5 To ActiveSheet.Cells(Rows.Count, 5).End(xlUp).Row Step 2

Set xlMerge = Range(Cells(i, 1), Cells(i + 1, 1))
With xlMerge
.Merge
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
End With
Next i

For j = 5 To ActiveSheet.Cells(Rows.Count, 5).End(xlUp).Row Step 2

Set xlMergeJ = Range(Cells(j, 2), Cells(j + 1, 1))
With xlMergeJ
.Merge
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
End With
Next j

最佳答案

也许你正在追求这个:

Option Explicit

Sub main()
Dim i As Long

With ActiveSheet
For i = 5 To .Cells(Rows.count, 1).End(xlUp).row Step 2
With .Cells(i, 1).Resize(2)
.Merge
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
End With
With .Cells(i, 2).Resize(2)
.Merge
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
End With
Next i
End With
End Sub

或其较短的选项:

Sub main()
Dim i As Long

With ActiveSheet
For i = 5 To .Cells(Rows.count, 1).End(xlUp).row Step 2
With .Range(.Cells(i, 1).Resize(2).Address & "," & .Cells(i, 2).Resize(2).Address)
.Merge
.HorizontalAlignment = xlCenterAcrossSelection
.VerticalAlignment = xlCenter
End With
Next i
End With
End Sub

关于VBA用循环合并单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41357662/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com