Failing to copy one cell to another cell using Destination Copy

青春壹個敷衍的年華 提交于 2020-01-25 09:04:35

问题


Range("A1").Copy (Range("E5"))

That fails, but if I explicitly define the destination range as a Destination, like the following, it works.

Range("A1").Copy Destination:=Range("E5")

If I give a Worksheet reference for my destination, like the following, it also works:

Range("A1").Copy (Worksheets("Sheet1).Range("E5"))

Why is the simplest form, not working, and giving me

Runtime Error 1004: "Copy method of Range class failed"

instead?


回答1:


The difference between

Range("A1").Copy (Range("E5"))

and

Range("A1").Copy Range("E5")

is that the first one converts the ByRef argument into ByVal while the second does not. The parenthesis here stands for a conversion and not for what you expected.

Note that you must only use the parenthesis when you use a function (that returns a value) but not when using a procedure.

Example

a = MyFunction(Parameter1, Parameter2)   'correct with parenthesis
MyProcedure Parameter1, Parameter2       'correct w/o parenthesis

a = MyFunction Parameter1, Parameter2    'it will error
MyProcedure(Parameter1, Parameter2)      'it will error

now with only one parameter

a = MyFunction(Parameter1)   'correct with parenthesis
MyProcedure Parameter1       'correct w/o parenthesis

a = MyFunction Parameter1    'it will error
MyProcedure (Parameter1)     'it will NOT error but convert ByRef into ByVal !!!

The last line of the above example does something completly different than you expected. You can notice the extra space between the procedure name and the parenthesis. And it is the same like the following syntax

a = MyFunction((Parameter1), (Parameter2))   'convert ByRef into ByVal
MyProcedure (Parameter1), (Parameter2)       'convert ByRef into ByVal

So we can note down:

  • If a function returns a value that we want to write into a variable:
    You must use parenthesis: a = MyFunction(Parameter1)
  • If a procedure (or function) does not return a value then:
    You must not use parenthesis: MyProcedure Parameter1



回答2:


you have to eliminate brackets

Range("A1").Copy Range("E5")


来源:https://stackoverflow.com/questions/58864512/failing-to-copy-one-cell-to-another-cell-using-destination-copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!