Quicker alternative to `resize`?

2019-08-08 03:37发布

Per @ScottHoltzman's suggestion. I am setting certain columns from one book to another book. resize is proving to be very slow. What's a quicker method? I probably only need 200 rows max from each column.

With ws
        .Columns(Start).Resize(, 2).Value = book.Worksheets(wsName & "-F").Columns("A:B").Value
        .Columns(Start + label).Resize(, cols).Value = book.Worksheets(wsName & "-F").Columns(Start + label).Resize(, cols).Value
End With

1条回答
祖国的老花朵
2楼-- · 2019-08-08 04:05

This statement ws.Columns(1).Resize(, 2) translates to "2 million+ rows from column 1 and 2"

The solution you found works well but it's not dynamic (hard-coded last row)

This is how I'd setup the copy of columns:

Option Explicit

Public Sub copyCols()
    Dim ws1 As Worksheet, ws2 As Worksheet, rng1 As Range, rng2 As Range
    Dim cols As Long, lr As Long

    Dim col1 As Long    'renamed from "Start" (VBA keyword - property)
    Dim lbl As Long     'renamed from "label" (VBA keyword - Control object)

    Set ws1 = Sheet1    'ws
    Set ws2 = Sheet2    'book.Worksheets(wsName & "-F")

    col1 = 1
    cols = 2
    lbl = 1

    lr = ws2.Cells(ws2.UsedRange.Row + ws2.UsedRange.Rows.Count, "A").End(xlUp).Row

    Set rng1 = ws1.Range(ws1.Cells(1, col1), ws1.Cells(lr, col1 + 1))
    Set rng2 = ws2.Range("A1:B" & lr)

    rng1.Value2 = rng2.Value2

    Set rng1 = ws1.Range(ws1.Cells(1, col1 + lbl), ws1.Cells(lr, col1 + lbl + cols))
    Set rng2 = ws2.Range(ws2.Cells(1, col1 + lbl), ws2.Cells(lr, col1 + lbl + cols))

    rng1.Value2 = rng2.Value2 
End Sub
查看更多
登录 后发表回答