将 1x12 表格中的单元格垂直合并为三个块

问题描述 投票:0回答:1

我在 MS Word 中有一个表格。 它的宽度为 1 个单元格,向下 12 个单元格,每个单元格包含一个数字。 我想使用 VBA 将 12 个单元格合并为 4 个包含 3 个数字的单元格。

因此,如果 12 个单元格各自包含数字 1 到 12,我希望最终有 4 个单元格。 单元格 1 包含 1 2 3 单元格 2 包含 4 5 6 单元格 3 包含 7 8 9 单元格 4 包含 10 11 12

我已经要求 ChatGPT 编写代码,在更正其错误后,我得到了这个:

Sub MergeCellsVertically()
    Dim tbl As Table
    Dim i As Integer
    
    ' Set tbl to the first table in the document
    Set tbl = ActiveDocument.Tables(1)
    
    ' Loop through each row in the table
    For i = 1 To tbl.Rows.Count 'Step 3
        ' Check if there are at least three rows remaining
        If i + 2 <= tbl.Rows.Count Then
            ' Merge the cells in the first column
            tbl.Cell(i, 1).Merge tbl.Cell(i + 1, 1)
            tbl.Cell(i, 1).Merge tbl.Cell(i + 2, 1)
        End If
    Next i
End Sub

但这给了我 3 个包含 4 个数字的单元格: 1 2 3 4 5 6 7 8 9 10 11 12。 我尝试过使用代码中的参数,但无法将 12 合并为 4 个 3 块,只有 3 个 4 块。我显然错过了一些明显的东西,但是什么呢?

vba merge ms-word
1个回答
0
投票
Option Explicit

Sub MergeCellsVertically()
    Dim tbl As Table
    Dim i As Long, j As Long, iR As Long
    ' Set tbl to the first table in the document
    Set tbl = ActiveDocument.Tables(1)
    ' Loop through each row in the table
    For i = tbl.Rows.Count To 1 Step -3
        iR = i
        For j = 1 To 2
            tbl.Cell(iR, 1).Merge tbl.Cell(iR - 1, 1)
            iR = iR - 1
        Next
    Next i
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.