Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How make concatenate function faster

Tags:

excel

vba

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

like image 692
user9585960 Avatar asked Jan 02 '23 14:01

user9585960


1 Answers

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
like image 119
paul bica Avatar answered Feb 27 '23 23:02

paul bica