简体   繁体   English

如何在Excel / VBA中的单元格范围内进行迭代?

[英]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. 我尝试了3个不同的选项,但仍然收到错误消息。 I'm new to VBA and still learning. 我是VBA的新手,仍然在学习。 How can I fix this, and why am I getting the error? 如何解决此问题,为什么会出现错误?

One problem is the line myrange = works.Range("C1:C9") . 一个问题是myrange = works.Range("C1:C9") It should have Set before it, like: 它前面应该有Set ,例如:

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. 没有它,您将告诉VBA您希望将单元格的值放入变量中。 With it, you're telling VBA that you want your variable to point to that range. 有了它,您就告诉VBA您希望变量指向该范围。

Since you did not explicitly declare myrange as a Range object, VBA implicitly declared it Variant and treated it as a String . 由于您没有明确将myrange声明为Range对象,因此VBA隐式声明了Variant并将其视为String So, in the loop, txt was a String too, not a Range as you expected. 因此,在循环中, txt也是String ,而不是您期望的Range 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. 如果您在一开始就有Dim myrange As Range ,则没有Set的分配将会失败,并且您将立即修复它。

But there's a simple habit that prevents this kind of error: in the top of your module, insert Option Explicit . 但是有一个防止这种错误的简单习惯:在模块顶部,插入Option Explicit This way, you have to explicitly declare ALL your variables, which means VBA won't assume they're Variant . 这样,您必须显式声明所有变量,这意味着VBA不会假定它们是Variant

You can even make that automatic by checking the relevant option in Tools > Options . 您甚至可以通过选中“ Tools > Options的相关选项来使其自动化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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