简体   繁体   English

(VBA-Excel)高效传输大范围的方法

[英](VBA-Excel) Efficient way to transfer a large range

I was wondering, which would be more efficient for a transfer of a large range of cells (about 100 000 cells - 10 000 x 10) between workbooks or worksheets: 我想知道,在工作簿或工作表之间传输大量单元格(大约100 000个单元格 - 10 000 x 10)会更有效:
1. Copying and pasting as values: 1.复制和粘贴为值:

rng1.Copy
rng2.PasteSpecial xlValues
Application.CutCopyMode=False


2. Passing only the values with .Value: 2.仅使用.Value传递值:

rng2.Value = rng1.value
'The ranges will be predefined to be the same size


Thanks for the help in advance! 我在这里先向您的帮助表示感谢!

I'm pretty sure your second option is best, but formatting won't be transferred. 我很确定你的第二个选项是最好的,但格式化不会被转移。 You may want to consider using Value2 instead, there is a performance improvement over using Value . 您可能希望考虑使用Value2 ,与使用Value相比,性能有所提高。

rng2.Value2 = rng1.value2

Edit 1 编辑1

After doing some testing, I'm surprised to see that copy/paste can be faster, about 5 times faster with the testing below, but this is with a mostly empty range. 在做了一些测试之后,我很惊讶地看到复制/粘贴可以更快,在下面的测试中快5倍,但这是大多数空的范围。 Also, Value2 reaches an out of memory error sooner. 此外, Value2更快地达到内存不足错误。 That being said, Value2 is cleaner code and it doesn't wipe out your clipboard contents, something to think about. 话虽这么说, Value2是更清晰的代码,它不会消除你的剪贴板内容,需要考虑的事情。

Public Declare Function GetTickCount Lib "kernel32.dll" () As Long
Sub test()
    Dim r1, r2 As Range
    Dim t As Long

    Set r1 = Sheets("S1").Range("A1:Z100000")
    Set r2 = Sheets("S2").Range("A1:Z100000")

    'Method1
    t = GetTickCount
    r1.Copy
    r2.PasteSpecial xlValues
    Debug.Print GetTickCount - t

    'Method 2
    t = GetTickCount
    r2.Value2 = r1.Value2
    Debug.Print GetTickCount - t

End Sub

Edit 2 编辑2

Previous testing was with a mostly empty range. 以前的测试大多是空的。 Filling the range with a Table and filing the table with content shows that Value2 is ~40% faster at handling the full range, but it always handles the full range. 使用表格填充范围并使用内容填充表格显示, Value2在处理整个范围时快了约40%,但它始终处理整个范围。 I suspect that the difference may be that Copy/Paste has the advantage of being more superficial and thereby realizes a performance gain if empty cells are present. 我怀疑差异可能是复制/粘贴具有更肤浅的优点,从而在存在空单元格时实现性能提升。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM