简体   繁体   English

为什么我会从此代码中收到VBA运行时错误“ 424”对象必需错误?

[英]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 . 在我的Excel工作表中,我有一个名为su_callLog的单元格。

My VBA code is: 我的VBA代码是:

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. 即使当我尝试仅打印Range的内容时,也会收到VBA Run-time error '424' Object Required错误。 I'm new to VBA. 我是VBA的新手。 Please tell me what I'm doing wrong. 请告诉我我在做什么错。

NOTE: MsgBox (Range("su_callLog")) produces the expected results. 注意: MsgBox (Range("su_callLog"))产生预期的结果。

Remove the parentheses: 删除括号:

CopyCell Range("su_callLog") 

If you use parentheses, you are forcing that the arguments are taken ByVal . 如果使用括号,则将强制参数采用ByVal And the Range() is an object type, which is passed ByRef . Range()是一个对象类型,该对象类型通过ByRef

ByVal vs ByRef VBA ByVal和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. 正如@Vityata正确指出的那样,您在需要将引用传递给范围的同时,强制使用ByVal

While that much is true and CopyCell Range("su_callLog") will produce the desired result, there is one more way to achieve this: 尽管确实如此, CopyCell Range("su_callLog")会产生所需的结果,但是还有另一种方法可以实现:

in which you implicity reference the Range correctly while in parentheses 在其中用括号正确隐式地引用Range
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 此外, 每次使用Range对象时都使用特定的Sheet是一个很好的VBA编码惯例

So to speak, you sort of kill two birds with one stone here 可以这么说,你用一块石头杀死了两只鸟

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM