Reputation: 125
So, sometimes when I try to execute this command, it gives me an error. The problem is that it is very inconsistent. In certain cases, it works and in others, it just doesn't.
This is the line from getCellVal function. cellName is a string and s is an integer.
getCellVal = Sheets(s).Range(cellName).Value
This time it is giving me: Run-time error '438': Object doesn't support this property or method
This line actually worked without problems moments ago. I added some other functions that use it and now it's not working anymore.
Any ideas about why?
Upvotes: 2
Views: 2520
Reputation: 71157
Unqualified calls into the Sheets
collection implicitly refer to whatever workbook is currently active, and it's important to know that the collection contains Worksheet
objects, ...but also Chart
objects.
Since you mean to work with a Worksheet
, use the Worksheets
collection instead.
If you're not getting an "index out of bounds" error, then the sheet you asked for does exist. But error 438 points to that sheet not being a Worksheet
(and thus not having a Range
member).
I bet the active workbook has a chart sheet at index s
.
The solution is simply to be explicit.
If you mean to work with the workbook that contains the code that's running, qualify Workbook
member calls with ThisWorkbook
:
getCellVal = ThisWorkbook.Worksheets(s).Range(cellName).Value
If you mean to work with a workbook, then you need to get ahold of the Workbook
object when you open it:
Dim wb As Workbook
Set wb = Application.Workbooks.Open(path)
'...
getCellVal = wb.Worksheets(s).Range(cellName).Value
Upvotes: 3