简体   繁体   中英

How to iterate over a range of cells in Excel/VBA?

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM