Search code examples
excelvbacopy-pasteworksheet-function

Is there a faster way to copy cell values from one sheet to another if the number of rows and columns keep changing


I am trying to make the most general macro to transfer data from one cell to another at the moment I am copy cell by cell to a var and setting the values that way but this really slows things down any ideas?

 For i = TableDataRowNum To lastDataRow - 1
        For activeCounter = 0 To colCount
            aCellValue = ServiceTemp.Cells(TableDataRowNum + printCounter, activeCounter + 1).Text
            aSheet.Cells(rowCount + printCounter, activeCounter + 1).value2 = "'" & aCellValue
            aSheet.Cells(rowCount + printCounter, activeCounter + 1).Font.colorIndex = colorValue
        Next
        printCounter = printCounter + 1
        statusBarCounter = statusBarCounter + 1
        If statusBarCounter = 450 Then
             theStatus.ShowStatus "Formatting Data To WorkSheet " & aSheet.Name & " " & printCounter & " Rows Processed"
             statusBarCounter = 1
        End If
    Next

Solution

  • Not enough reputation to comment, but if you have a continuous range, and you know the starting cell, which you can put in a variable, then you can define the range to copy like below and paste to set destination:

    Dim luc As Range
    Dim src As Range
    Dim dest As Range
    
    Set luc = Cells(1, 1)
    Set dest = Cells(10, 1)
    
    
    Set src = Range(luc, luc.End(xlToRight))
    Set src = Range(src, src.End(xlDown))
    
    src.Copy
    
    dest.PasteSpecial (xlPasteAll)
    

    You could wrap this in a sub that takes the left upper corner of the source and target ranges as input.