Excel VBA宏:"For Each ... In ..."循环中的"Object required"

emb*_*end 5 excel vba excel-vba

这是Excel 2013中的VBA宏.

我正在循环播放Sheet 1,Col B中的单元格.对于每个单元格,我想要取其值并在Sheet 2,Col A中搜索.如果找到,我想在Sheet 2,Col中取相应的值B并将其放在Sheet 1,Col E中的相应行中.

这些表:

Tagging                 Automatic Categories
B     E                 A     B
hat                     cake  Delicious cake.
cake
arm
Run Code Online (Sandbox Code Playgroud)

应该成为:

Tagging                 Automatic Categories
B     E                 A     B
hat                     cake  Delicious cake.
cake  Delicious cake.
arm
Run Code Online (Sandbox Code Playgroud)

码:

Sub AutoCategorize()
Dim c As Range
Dim searchRng As Range
For Each c In Sheets("Tagging").Range("B6:B500").Cells ' loop through cells to do the lookup based on
    If Not c.Value Is Nothing Then ' if there is something in the cell
        If c.Offset(0, 3).Value Is Nothing Then ' make sure the cell to fill is empty
            With Sheets("Automatic Categories").Range("A2:A500") ' using the cells we're looking up in...
                Set searchRng = .Find(What:=c.Value) ' find it
                If Not searchRng Is Nothing Then ' make sure we've found a thing
                    If Not searchRng.Offset(0, 1).Value Is Nothing Then ' make sure it has a corresponding entry
                        Set c.Offset(0, 3).Value = searchRng.Offset(0, 1).Value ' fill it in
                    End If
                End If
            End With
        End If
    End If
Next
End Sub
Run Code Online (Sandbox Code Playgroud)

我认为,我的问题在于我对Excel-VBA如何构建数据的理解.遗憾的是,MSDN在这方面确实无益,而且我只是设法将很多事情从实验中解放出来.

当我运行代码时,我得到了

Run-time error '424': Object required
Run Code Online (Sandbox Code Playgroud)

并调试器突出显示

If Not c.Value Is Nothing Then
Run Code Online (Sandbox Code Playgroud)

任何人都可以了解导致错误的原因吗?我很确定我的逻辑是可以的,但正如我所说,我不是100%关于如何引用单元格/数据结构如何工作.

我是VB和Excel宏的新手,如果有更好的方法来构建东西,那就大喊大叫.这也是我的第一篇StackOverflow帖子,如果我做错了什么,请告诉我.

cit*_*ong 4

这里的错误是If Not c.Value Is Nothing检查单元格 c 中包含的值是否是一个对象,并且该对象尚未实例化。

由于单元格值是原始类型(实际上是变体),因此要使用的正确检查是

If c.Value <> vbNullString

或者

If IsEmpty(c)

您稍后使用Is Nothing, inIf Not searchRng Is Nothing是正确的,因为这是检查 Range 对象是否包含Nothing.