Reputation: 11
Dim works As Worksheet
Set works = ThisWorkbook.Sheets("Sheet1")
Dim txt As Variant
myrange = works.Range("C1:C9")
For Each txt In myrange
If InStr(1, txt, "£", vbTextCompare) > 0 Then
Debug.Print txt.Value '<..Object required err
Debug.Print works.Range("C" & txt).Value '<..Object required err
Debug.Print works.Cells(txt, 1).Value '<..Object required err
Debug.Print txt.Offset(0, 1).Value '<..Object required err
End If
Next txt
I'm trying to get the value of the cell that contains the "£" and then delete it . I'm getting `the object defined error in any case. I've tried 3 different options and still getting the error. I'm new to VBA and still learning. How can I fix this, and why am I getting the error?
Upvotes: 0
Views: 267
Reputation: 14112
One problem is the line myrange = works.Range("C1:C9")
. It should have Set
before it, like:
Set myrange = works.Range("C1:C9")
This way you ensure you are making a reference assignment, instead of a value assignment. Without it, you're telling VBA that you want the value of the cells to go in your variable. With it, you're telling VBA that you want your variable to point to that range.
Since you did not explicitly declare myrange
as a Range
object, VBA implicitly declared it Variant
and treated it as a String
. So, in the loop, txt
was a String
too, not a Range
as you expected. Hence your error.
If you had Dim myrange As Range
in the beginning, your assignment without Set
would have failed and you'd have fixed it immediately.
But there's a simple habit that prevents this kind of error: in the top of your module, insert Option Explicit
. This way, you have to explicitly declare ALL your variables, which means VBA won't assume they're Variant
.
You can even make that automatic by checking the relevant option in Tools > Options
.
Upvotes: 1