2014-02-19 46 views
0

我在运行宏时收到对象变量错误。代码中的对象变量错误

Object Variable or with block variable not set

这发生在所述第二时间我运行通过宏。这里是导致错误的代码:

' Select the first Junk Row and use it to delete all rows afterward 
    With ActiveSheet 
     LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row 
    End With 

    With Columns("F") 
     .Find(What:="Total", After:=.Cells(1, 1), LookIn:=xlValues).Activate - **Error occurs here.** 
    End With 
    A = ActiveCell.Row 
    Range(A & ":" & LastRow).Delete 

任何建议将不胜感激。如果我关闭该程序,它会在下次通过时正常工作。

感谢, 斯科特

+0

你'查找()'没有找到匹配... –

+0

不知道为什么它没有我手动经历,看到有一个匹配。自从通过使用另一列创建了解决方法之后,我想知道为什么会发生这种情况。谢谢。 – SASUSMC

+0

蒂姆是对的。另外'.Find'参数'LookAt'默认设置为'xlPart',所以如果真的存在'Total',即使你有尾随或前导空格,它也会找到它。 – L42

回答

0

在激活单元之前。它很好地检查.find是否找到了单元格。下面是例子。

测试

Sub testing() 
Dim rng As Range 
    With ActiveSheet 
     LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row 
    End With 

    With Columns("F") 
     Set rng = .Find(What:="Total", After:=.Cells(1, 1), LookIn:=xlValues) 
    End With 

    If Not rng Is Nothing Then 

    A = rng.Row 

    Range(A & ":" & LastRow).Delete 

    Else 

    MsgBox ("Total not found") 

    End If 

End Sub 
1

第一次运行该代码会删除底部行包括含有“总计”行。第二次运行代码时失败,因为第一次删除了“总计”

0

尝试和更换

.find (...).activate 

由:

.find (...).select 

即使我不同意使用select /激活。

最简单的是

A= .find (....) .row 
'might return 0 or <nothing> or error , if no match (.match is faster by the way) 
相关问题