如何使连接功能更快

时间:2018-04-02 23:17:30

标签: excel vba excel-vba

大家好,希望你做得好。我有一个代码,它依赖于稍后使用的连接过程。我进行连接的代码片段如下:

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

问题是如果我有一个大样本,它需要太多时间才能完成。你们知道如何让它变得更好更快吗?提前致谢

3 个答案:

答案 0 :(得分:3)

有几种方法可以在没有循环的情况下一次性分配所有内容。例如:

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

答案 1 :(得分:3)

批量加载数组,处理所述数组然后将结果放回工作表 en masse 几乎总是比循环快得多。

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

答案 2 :(得分:3)

公式和数组之间的区别:

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