简体   繁体   中英

Run time Error - 438

I have the following code in which I am trying to copy data from one sheet to another in same workbook. When I run the code I get Runtime error -438

Sub Copy()

Sheets("Sheet1").Range("A1:D20").Copy

Sheets("Sheet2").Activate

Range("E1").Select

ActiveSheet.Paste

Application.CutCopyMode = False

End Sub

Try the following code. You should not rely on Activate and Select.

Sub ZCopy()
    Sheets("Sheet1").Range("A1:D20").Copy
    Sheets("Sheet1").Paste Destination:=Worksheets("Sheet2").Range("E1")
    Application.CutCopyMode = False
End Sub

Interesting Reads

  1. MSDN
  2. How to avoid using Select in Excel VBA macros

Do you have a particular need for copy and paste? This can be slow and inefficient. If you're just copying data from one sheet to another, you can set the values of one range equal to the values of another range and avoid the whole thing.

Sheets("Sheet2").Range("E1:H20").Value = Sheets("Sheet1").Range("A1:D20").Value

This will set the range from cells E1:H20 on Sheet2 to the same values as those in the range A1:D20 on Sheet1, which is effectively a copy and paste. I should add that this will work only for the values themselves.

If there is specific formatting (or formulas) that you need copied and pasted, this method won't work.

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