简体   繁体   中英

Excel VBA Copy and paste range

In my sheet I calculate the prime factors for a number, the range is from E6 onwards. I have the following line of code to determine the number of rows.

rCount = Application.WorksheetFunction.CountA(Range("E:E")) - 1

The minus 1 is to exclude the header and get only the range containing numbers. I have also set the range and copied as follows:

Set rgCopy = Range("E6", Selection.End(xlDown))
    Selection.Copy

However, when I try to paste this in a cell it gives me the following error:

Run-time error '1004':
Method 'Range' of object'_Global' failed

Here's the coding I have so far

Dim rgCopy As Range
    Dim rCount As Integer

    Set rgCopy = Range("E6", Selection.End(xlDown))
    Selection.Copy
    rCount = Application.WorksheetFunction.CountA(Range("E:E")) - 1
    lastrow = Cells(Rows.Count, 4).End(xlUp).Row

    Range("E6:" & Selection.End(xlDown)).Copy Destination:=Range("D" & lastrow + 5)

Any assistance would be appreciated.

This works:

Sub test()
Application.ScreenUpdating = False
Dim LastRow As Long
LastRow = ActiveSheet.Cells(Rows.Count, "E").End(xlUp).Row

ActiveSheet.Range("E6:E" & LastRow).Copy

LastRow = ActiveSheet.Cells(Rows.Count, "D").End(xlUp).Row

ActiveSheet.Range("D" & LastRow + 5).PasteSpecial xlPasteAll
Application.ScreenUpdating = True
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