Search code examples
excelcopy-pastevba

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.enter image description here


Solution

  • 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