Excel宏一次连接一行到文件结尾

时间:2012-04-25 15:05:54

标签: excel vba excel-vba concatenation

我需要一个Excel宏来连接每行的七列数据,直到到达数据的末尾。例如,如果我有这样的公式:

=A1&B1&C1&D1&E1&F1&G1

如何编写宏,以便按照这样的顺序将每行增加到文件的末尾?

=A1&B1&C1&D1&E1&F1&G1
=A2&B2&C2&D2&E2&F2&G2
=A3&B3&C3&D3&E3&F3&G3

3 个答案:

答案 0 :(得分:3)

有了这么多的答案,主要关注的是什么是我自己突出的assylias已经浪费了:)

但是,如果您仍想要VBA答案。使用此方法。这比<{1}}或Looping 更快

Autofill

如果您有1000行,那么您可能需要在运行代码之前关闭Option Explicit Sub Sample() Dim LastRow As Long Dim Ws As Worksheet Set Ws = Sheets("Sheet1") LastRow = Ws.Range("A" & Ws.Rows.Count).End(xlUp).Row '~~> If your range doesn't have a header Ws.Range("H1:H" & LastRow).Formula = "=A1&B1&C1&D1&E1&F1&G1" '~~> If it does then Ws.Range("H2:H" & LastRow).Formula = "=A2&B2&C2&D2&E2&F2&G2" End Sub 并将Screenupdating更改为手动,然后在代码末尾重置它们。

答案 1 :(得分:0)

我认为最简单的方法是按照assylias的说法填写,但如果你想使用VBA:

Selection.AutoFill Destination:=Range("Your Fill Range"), Type:=xlFillDefault

应该复制其他行。

答案 2 :(得分:0)

我同意100%的评论和其他答案,为什么你需要VBA来做这件事,但只是为了回答你原来的问题,我就是这样做的:

Sub FillAllWithFormula()
Dim i As Variant
Dim wsht As Worksheet

    'If you are using this for a specific Worksheet use the following
    Set wsht = ThisWorkbook.Worksheets(yourWorksheetName)

    'or if you are always using this for the active sheet use the following
    Set wsht = ActiveSheet

    For i = 1 To wsht.Rows.Count
        'Replace "X" with the column letter you want your formula to appear in
        wsht.Range("X" & i).Formula = "=A" & i & "&B" & i & "&C" & i & "&D" & i & "&E" & i & "&F" & i & "&G" & i
    Next

    Set wsht = Nothing

End Sub