user9585960
user9585960

Reputation: 111

How make concatenate function faster

Hi everyone hope you are doing well. I have a code that depends on a concatenate process to be used later. The piece of code where I make the concatenate is the following:

i=2 
Do while ws.cells(i,2) <> 0
 ws.cells(i,1) = "=concatenate(C" & i & ", D" & i & ")" 
 i = i + 1 
Loop

The problem is if I have a big sample, it takes too much time to complete. Do you guys know any way to make it better and faster? Thanks in advance

Upvotes: 4

Views: 758

Answers (3)

paul bica
paul bica

Reputation: 10715

Difference between Formulas and Arrays:

Formula - Total Rows: 1,048,576, Time: 2.414 sec
Arrays  - Total Rows: 1,048,576, Time: 3.758 sec

Option Explicit

Public Sub JoinCDinA1()
    Dim ws As Worksheet, lr As Long, tr As String, t As Double

    t = Timer
    Set ws = Sheet1
    lr = ws.UsedRange.Rows.Count

    With ws.Range("A2:A" & ws.UsedRange.Rows.Count)
        .Formula = "= C2 & D2"
        .Value2 = .Value2
    End With

    tr = "Formula - Total Rows: " & Format(lr, "#,###,###")
    Debug.Print tr & ", Time: " & Format(Timer - t, "0.000") & " sec"
End Sub

Public Sub JoinCDinA2()
    Dim ws As Worksheet, ur1 As Variant, ur2 As Variant, r As Long, lr As Long
    Dim tr As String, t As Double

    t = Timer
    Set ws = Sheet1
    lr = ws.UsedRange.Rows.Count
    ur1 = ws.Range(ws.Cells(2, 1), ws.Cells(lr, 1))
    ur2 = ws.Range(ws.Cells(2, 3), ws.Cells(lr, 4))
    For r = 1 To lr - 1
        ur1(r, 1) = ur2(r, 1) & ur2(r, 2)
    Next
    ws.Range(ws.Cells(2, 1), ws.Cells(lr, 1)) = ur1

    tr = "Arrays  - Total Rows: " & Format(lr, "#,###,###")
    Debug.Print tr & ", Time: " & Format(Timer - t, "0.000") & " sec"
End Sub

Upvotes: 3

user4039065
user4039065

Reputation:

Bulk loading an array, processing said array then dropping the results back to the worksheet en masse is almost always appreciably faster than a loop.

dim i as long, vals as variant
with worksheets("sheet1")
    vals = .range(.cells(2, "C"), .cells(.rows.count, "B").end(xlup).offset(0, 2))
    for i=lbound(vals, 1) to ubound(vals, 1)
        vals(i, 1) = join(array(vals(i, 1), vals(i, 2)), vbnullstring)
    next i
    redim preserve vals(lbound(vals, 1) to ubound(vals, 1), 1 to 1)
    .cells(2, "A").resize(ubound(vals, 1), 1) = vals
end with

Upvotes: 3

Slai
Slai

Reputation: 22876

There are few ways to assign all at once without loop. For example:

ws.Range("A2:A" & ws.UsedRange.Rows.Count - 1).Formula = "= C2 & D2"

Upvotes: 3

Related Questions