VBA:复制和粘贴数据行的最快方法

时间:2017-01-29 11:58:05

标签: excel vba excel-vba

我想知道是否有更快捷的方法将数据从工作表的一列复制并粘贴到工作表的另一列。这是我所拥有的示例代码,它运行缓慢,因为它要为我正在复制的每个列复制超过10000行数据。我正在复制的数据没有固定的范围。

For i = 2 To lastrow
    ws.Cells(i, "AG") = bl.Cells(i, "F")
    ws.Cells(i, "AH") = bl.Cells(i, "G")
    ws.Cells(i, "AB") = bl.Cells(i, "N")
    ws.Cells(i, "AC") = bl.Cells(i, "R")
    ws.Cells(i, "BF") = bl.Cells(i, "S")
    ws.Cells(i, "AA") = bl.Cells(i, "U")
    ws.Cells(i, "BA") = bl.Cells(i, "X")
    ws.Cells(i, "BQ") = bl.Cells(i, "AA")
    ws.Cells(i, "B") = bl.Cells(i, "AB")
    ws.Cells(i, "A") = bl.Cells(i, "AD")
    ws.Cells(i, "BW") = bl.Cells(i, "AK")
    ws.Cells(i, "BH") = bl.Cells(i, "AL")
    ws.Cells(i, "BR") = bl.Cells(i, "AM")
    ws.Cells(i, "AL") = bl.Cells(i, "AP")
    ws.Cells(i, "AP") = bl.Cells(i, "BA")
    ws.Cells(i, "AQ") = bl.Cells(i, "BB")
    ws.Cells(i, "AU") = bl.Cells(i, "BC")
    ws.Cells(i, "AO") = bl.Cells(i, "BK")
    ws.Cells(i, "AT") = bl.Cells(i, "BO")
Next i

3 个答案:

答案 0 :(得分:2)

复制整列而不是单元格!

ws.Range("AG2:AH" & lastrow) = bl.Range("F2:G" & lastrow) '2 cols at once here
ws.Range("AB2:AB" & lastrow) = bl.Range("N2:N" & lastrow) '.Value is implicit

(等等......)应该快1000倍。

VBA和Excel之间的数据交换对于CPU而言非常昂贵。因此,转移大块更有效。

答案 1 :(得分:0)

试试吧:

ws.Range("AG2:AG" & lastrow).Value = bl.Range("F2:F" & lastrow).Value
ws.Range("AH2:AH" & lastrow).Value = bl.Range("G2:G" & lastrow).Value
ws.Range("AB2:AB" & lastrow).Value = bl.Range("N2:N" & lastrow).Value

以及其他列

等等

答案 2 :(得分:0)

除了上面提供给我的答案之外,我发布了另一个类似的问题,其中有一个不同用户的另一个答案,我认为我应该在这里分享,以帮助其他人在SO中寻找。

https://stackoverflow.com/a/41951959/7483682

相关问题