简体   繁体   中英

VBA copy and paste code not working

I am trying to copy column from one sheet to another. To avoid 'Select', I wrote code like worksheet.range.copy. For some reason, code below is giving me error. If I replace Range("A2").End(xlDown) with lets say "A100" then code will work.

Sub CopyData()

    MTDData.Range("A2", Range("A2").End(xlDown)).Copy
    MTDFormula.Range("H2").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

End Sub

Any suggestion why the code above giving error and is there a more efficient way to copy and paste large chunk of data from one sheet to another. 在此处输入图片说明

You need to add the parent sheet to the range inside the range:

MTDData.Range("A2", MTDData.Range("A2").End(xlDown)).Copy
MTDFormula.Range("H2").PasteSpecial Paste:=xlPasteValuesAndNumberFormats

But we can use a With block and save some typing and space. Also you do not need the pastespecial.

With MTDData
    .Range("A2", .Range("A2").End(xlDown)).Copy MTDFormula.Range("H2")
End with

The fastest way to copy large sets of values is not to use the clipboard but the copy directly.

MTDFormula.Range("H2").Resize(n,1).Value = MTDData.Range("A2").Resize(n,1).Value

but you have to find the size of the cells first. This is done with the following reusable piece of code:

Public Function CountRows(ByRef r As Range) As Long
    If IsEmpty(r) Then
        CountRows = 0
    ElseIf IsEmpty(r.Offset(1, 0)) Then
        CountRows = 1
    Else
        CountRows = r.Worksheet.Range(r, r.End(xlDown)).Rows.Count
    End If
End Function

So your copying code would look like this:

Public Sub CopyValuesTest()

    Dim src As Range, dst As Range

    Set src = MTDData.Range("A2")
    Set dst = MTDFormula.Range("H2")

    Dim n As Long
    n = CountRows(src)

    dst.Resize(n, 1).Value = src.Resize(n, 1).Value
    dst.Resize(n, 1).NumberFormat = src.Resize(n, 1).NumberFormat
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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