0

I am trying to determine the column number of a header in an Excel spreadsheet using the following VBA code:

Dim aCell As Range
Set aCell = Sheet1.Rows(1).Find(What:="ContractDescription", LookIn:=xlValues, _
 LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
 MatchCase:=False, SearchFormat:=False)

Then the following line of code gives an error:

MsgBox (aCell.Column)

It gives the run-time error 91: "Object variable or With block variable not set".

According to posts that I have read on the internet, this error occurs when you are trying to assign a value of one type to a variable that has been declared as a different type.

However, I am trying to understand why I am getting this error here since aCell is a range object and I am simply taking aCell.Column, but when I do Range("A1").Column I do get the valid 1 printed on the screen.

So what may be causing the problem here?

1
  • You might also wanna see THIS Commented Oct 7, 2013 at 12:34

2 Answers 2

3

If .Find fails it will return & set aCell to Nothing so attempting to access any instance members like .Column will raise that error.

To guard against this;

if not aCell Is Nothing
  MsgBox aCell.Column
else
  MsgBox "not found"
end if 
Sign up to request clarification or add additional context in comments.

Comments

2

The reason why you get this error is because aCell is null (no match was found). Before using a range from a Find method (or equivalent, where the range might be Nothing), you have to set a condition on the lines of:

If (Not aCell Is Nothing) Then
  MsgBox aCell.Column
End If

3 Comments

But since aCell is nothing, MsgBox doesn't get executed - how do I get MsgBox to be executed?
@Anonymous you are free to execute MsgBox outside the condition (or inside an Else with an error message, as suggested by Alex K.). But you cannot show what is not there and if aCell is Nothing the Column is also nothing (no range to show a column from). You are intending to show the column where certain value was found; but the value wasn't found and thus what do you want to show?
Oh I finally see! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.