创建一个循环以跨行合并列

时间:2014-07-14 15:27:36

标签: excel-vba vba excel

我在下面有第17行的代码。我试图将它从第17行循环到第26行,这样对于每一行,列B:K被合并并采用指定的格式(例如,换行文本)。我尝试了多种方式的do循环并且继续失败,有人可以帮忙吗?

    Sub SubmitData()

    Dim RngB As Range


        With Sheets("Field_Phase 1")
            Set RngB = Range("B17:K17")
            RngB.Merge
            RngB.Borders.LineStyle = xlContinuous
            RngB.HorizontalAlignment = xlLeft
            RngB.WrapText = True
       End With

    End Sub

1 个答案:

答案 0 :(得分:0)

For循环听起来更合适,因为您想要合并确定的行范围:17 - 26.

试试这个:

Sub SubmitData()

    Dim RngB As Range

    With Sheets("Field_Phase 1")

        Dim row As Long
        For row = 17 To 26
            Set RngB = .Range(.Cells(row, 2), .Cells(row, 11))
            RngB.Merge
            RngB.Borders.LineStyle = xlContinuous
            RngB.HorizontalAlignment = xlLeft
            RngB.WrapText = True
        Next row
   End With

End Sub

请注意将..Range.Cells语句相关联的With

你也可以这样做:

Set RngB = .Range("B" & row & ":K" & row)

但是,我更喜欢R1C1版本。