I am creating a VBA application, and I have the following code:
Dim previousCell As range
Private Sub Worksheet_SelectionChange(ByVal target As range)
Application.EnableEvents = False
On Error GoTo ws_exit:
Set previousCell = target
getEffort (previousCell) '**Here i get object required**
ws_exit:
Application.EnableEvents = True
MsgBox Err.Description
End Sub
Private Function getEffort(ByVal cell As range)
' do soemthing
End Sub
I'm not sure why I get the error message: Object required error at getEffort(previousCell)
. If I pass in the Target
, it works.
Thanks
The “Object required” means object data type reference needs to be accurate. When the Option Explicit word is unenabled in the coding, we will get an “Object Required” error for misspelled variable words. If Option Explicit is enabled, we will get the variable not defined error for misspelled variable words.
The simplest ways to fix the problem is as follows: Locate the offending line of code (if not highlighted, use debug mode) Identify whether you've referenced any objects which aren't declared. Look for any of the functions which may be causing an error and identify they are called correctly (with the correct syntax)
To do this, click on 'Tools' and then click on 'Options'. In the options dialog box, make sure that the 'Auto Syntax Check' option is enabled. If the 'Auto Syntax Check' option is disabled, VBA will still highlight the line with the syntax error in red, but it will not show the error dialog box.
As others have suggested, the problem is the parentheses. What no one has adequately explained is why it is the parentheses.
When you say this:
getEffort previousCell
Then you are passing the previousCell
Range object into the getEffort procedure. That is what the procedure expects and so it is happy.
When you say this:
getEffort (previousCell)
The parentheses around previousCell
cause VBA to evaluate the previousCell
object. When VBA evaluates an object it returns that object's default property. The default property of the Range object is .Value
, which is a string.
So previousCell is evaluated and a string gets passed on to getEffort. Of course getEffort is expecting a Range object, so you receive the error message.
The fact that you are assigning Target
to previousCell
is a red herring. You likely introduced the parentheses when you switched to previousCell
. If you don't believe me, try this:
getEffort (Target)
You will get the same error message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With