Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Required error Excel VBA

Tags:

excel

vba

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

like image 881
Ravi Avatar asked Sep 06 '12 17:09

Ravi


People also ask

What does error object required mean in VBA?

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.

How do you fix an object required?

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)

How do I fix a VBA error in Excel?

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.


1 Answers

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.

like image 186
mwolfe02 Avatar answered Oct 04 '22 04:10

mwolfe02