Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
You might also wanna see THIS –  Siddharth Rout Oct 7 '13 at 12:34
add comment

2 Answers

up vote 2 down vote accepted

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
share|improve this answer
    
+ 1 Spot On :-) –  Siddharth Rout Oct 7 '13 at 12:33
    
@SiddharthRout thanks :) –  varocarbas Oct 7 '13 at 12:34
    
But since aCell is nothing, MsgBox doesn't get executed - how do I get MsgBox to be executed? –  Adriaan Oct 7 '13 at 12:35
    
@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? –  varocarbas Oct 7 '13 at 12:36
    
Oh I finally see! Thank you! –  Adriaan Oct 7 '13 at 12:38
show 1 more comment

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 
share|improve this answer
    
+ 1 Spot On :-) –  Siddharth Rout Oct 7 '13 at 12:33
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.