简体   繁体   中英

Why do I get an VBA Run-time error '424' Object Required Error from this code?

In my excel sheet, I have a cell called su_callLog .

My VBA code is:

Private Sub su_callLogCopy_Click()
    CopyCell (Range("su_callLog")) 'Error Here
End Sub
Sub CopyCell(cell As Range)
    MsgBox cell.Value
End Sub

I'm trying to use the function to process the info in that cell. Even when i try to merely print the contents of the Range, I get the VBA Run-time error '424' Object Required error. I'm new to VBA. Please tell me what I'm doing wrong.

NOTE: MsgBox (Range("su_callLog")) produces the expected results.

Remove the parentheses:

CopyCell Range("su_callLog") 

If you use parentheses, you are forcing that the arguments are taken ByVal . And the Range() is an object type, which is passed ByRef .

ByVal vs ByRef VBA

As @Vityata correctly pointed oute, you're forcing ByVal to be taken, while you need to be passing a reference to a range.

While that much is true and CopyCell Range("su_callLog") will produce the desired result, there is one more way to achieve this:

in which you implicity reference the Range correctly while in parentheses
so in other words, you (knowingly or unknowingly) pass the reference properly.


 CopyCell (Sheets("Sheet1").Range("A1"))

Not only you maintain your desired (although unnecessary) braces syntax, but it actually works. Additionally it's a good VBA coding practice to be using a specific Sheet every time you're working with a Range object

So to speak, you sort of kill two birds with one stone here

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