Excel macro to concatenate one row at a time to end of file

空扰寡人 提交于 2021-02-10 05:49:09

问题


I need an Excel macro to join seven columns of data on each row until the end of the data is reached. For example if I have a formula like this:

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

How can I write the macro so that it increments for every row to the end of the file in a sequence like this?

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

回答1:


With so many answers, the main focus on what assylias and I were highlighting has gone to waste :)

However, if you still want a VBA answer. Use this method. This is much faster than Looping or an Autofill.

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

If you have 1000's of rows then you might want to switch off Screenupdating and change Calculation to Manual before you run the code and then reset them at the end of the code.




回答2:


I think the easiest way to do this would be to just fill down as assylias says but if you want to use VBA:

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

Should copy across the other rows.




回答3:


I agree 100% with the comments and the other answers, why do you need VBA to do this, but just to answer your original question, this is how I would accomplish it:

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


来源:https://stackoverflow.com/questions/10318431/excel-macro-to-concatenate-one-row-at-a-time-to-end-of-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!