更快速地替换`resize`?

时间:2015-10-16 20:54:46

标签: excel-vba vba excel

Per @ ScottHoltzman的建议。我正在设置从一本书到另一本书的某些专栏。事实证明resize非常缓慢。什么是更快的方法?我可能每列只需要200行。

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 个答案:

答案 0 :(得分:1)

此声明ws.Columns(1).Resize(, 2)转换为“第1列和第2列的200万+行”

您找到的解决方案运行良好但不是动态的(硬编码的最后一行)

这就是我设置列副本的方式:

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