Excel 未设置对象变量或带块变量。代码突然出现错误

Excel 未设置对象变量或带块变量。代码突然出现错误,excel,vba,Excel,Vba,请让我知道这个代码中的错误。几小时前,它工作正常,突然出现了错误 “未设置对象变量或带块变量” 它正在sheet1中查找数据,并将其高亮显示为黄色。标准见表2。您可以执行以下操作: Dim c As Range, f As Range Set c = Sheet2.Cells(1, 1) Do Until IsEmpty(c) Set f = ActiveSheet.Cells.Find(What:=c.Value, lookat:=xlWhole) 'got a match

请让我知道这个代码中的错误。几小时前,它工作正常,突然出现了错误

“未设置对象变量或带块变量”


它正在sheet1中查找数据,并将其高亮显示为黄色。标准见表2。

您可以执行以下操作:

Dim c As Range, f As Range

Set c = Sheet2.Cells(1, 1)

Do Until IsEmpty(c)
    Set f = ActiveSheet.Cells.Find(What:=c.Value, lookat:=xlWhole)
    'got a match?
    If Not f is nothing then
         'highlight the match
         With f.Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .Color = 65535
            .TintAndShade = 0
            .PatternTintAndShade = 0
         End With

         Sheet2.Cells(1, 3) = Sheet2.Cells(1, 3) + 1

         c.offset(0, 1).Value = "Found"
     End if

     Set c = c.offset(1,0) 'next row 
Loop
MsgBox "Total E-Forms Searched " & Sheet2.Cells(1, 3)

如果查找失败,则链接激活将引发错误。注释掉错误上的
,看看这是否是问题所在。我已经尝试过了,但没有效果。查找失败时会出现错误。请避免使用
ActiveSheet
。在@TimWilliams代码中加入该代码,然后重试。还要记住,
lookat:=xlWhole
将找到整个单词。也许你想看看:=xlPart?我非常感谢你的帮助。但有人能指出我代码中的确切问题吗。我想知道我的知识。不工作。虽然它不会给出任何错误,但也不会执行所需的任务。我猜您希望精确匹配,但可能不是这样?不管怎么说,您是否尝试过调试以查看什么不起作用?代码的“查找”部分显示错误。无法找出原因。对象变量或with block变量未设置哪一行?
Dim c As Range, f As Range

Set c = Sheet2.Cells(1, 1)

Do Until IsEmpty(c)
    Set f = ActiveSheet.Cells.Find(What:=c.Value, lookat:=xlWhole)
    'got a match?
    If Not f is nothing then
         'highlight the match
         With f.Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .Color = 65535
            .TintAndShade = 0
            .PatternTintAndShade = 0
         End With

         Sheet2.Cells(1, 3) = Sheet2.Cells(1, 3) + 1

         c.offset(0, 1).Value = "Found"
     End if

     Set c = c.offset(1,0) 'next row 
Loop
MsgBox "Total E-Forms Searched " & Sheet2.Cells(1, 3)