简体   繁体   中英

Slow copy paste in Excel vba

I have the below code and find that copy-pasting is slow and the interior colour is slow as well.

I am trying to deal with this code with 700,000 rows + 120 columns of data.

Any suggestion to improve the speed.

Currently, it can take me more than 20 mins to finish this row of code.

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.DisplayStatusBar = False

For i = keycolumns + 2 To ILcol + 1
    
    'Result.Cells(1, resultcolumn).EntireColumn.Insert
    rColumnLetter = Split(Cells(1, resultcolumn - 1).Address, "$")(1)
    iColumnLetter = Split(Cells(1, i - 1).Address, "$")(1)
    IL.Range(iColumnLetter & "1:" & iColumnLetter & ILrow).Copy Result.Range(rColumnLetter & "1:" & rColumnLetter & ILrow)
    colNum = Application.WorksheetFunction.Match(Result.Cells(1, resultcolumn - 1).Value, PL.Range("1:1"), 0)
    
    Result.Cells(1, resultcolumn) = Result.Cells(1, resultcolumn - 1) & " Postload - " & colNum
    
    'Result.Cells(1, resultcolumn + 1).EntireColumn.Insert
    Result.Cells(1, resultcolumn + 1) = Result.Cells(1, resultcolumn - 1) & " Comparison"
    ColumnLetter = Split(Cells(1, resultcolumn + 1).Address, "$")(1)
    Result.Range(ColumnLetter & "1:" & ColumnLetter & ILrow).Interior.Color = RGB(146, 208, 80)
    
    resultcolumn = resultcolumn + (2 * (i - i + 1)) + 1
    
    
Next i

In my experience it is better to avoid operations directly on the sheets. What I would do is:

  1. create an array variable
  2. resize the array so it can hold all the data
  3. populate the array with the actions currently included in your 'for' loop
  4. print the array into the sheet

The final result would be close to this:

public sub populateArray()
    dim arr_data() as Variant
    dim numberOfRows,numberOfColumns,currentRow,currentCollumn   as integer
    currentRow = 0
    currentCollumn = 0
    numberOfRows = 10
    numberOfColumns = 10
    redim arr_data(numberOfRows,numberOfColumns) 
    
    for currentRow to numberOfRows
        for currentCollumn to numberOfColumns
            arr_data (currentRow,currentCollumn) = "TEXT"
        next currentCollumn
    next currentRow
    
    with activesheet
        .range("A1") = arr_data
    next with
    
end sub

Please note that I did not test the above code, feel free to adjust it to your needs.

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