2014-04-23 35 views
1

我需要查找其中包含短语“总计”的每行,在其上方和下方插入行,在同一行内和周围格式化其他单元格,从单元格中删除短语“总计” ,并为报表中的所有其他行重复该过程。带有错误的循环完成

我开发的宏一旦找到并替换了所有“Total”实例,就会得到运行时错误'91':对象变量或块变量未设置。

我想完成循环而不会结束错误,因为这必须在多张纸上执行。这里是代码的肉:

'EmployerSummariesAddedForRegionsOnTabs Macro 
Dim FoundCell As Range, LastCell As Range 
Dim FirstAddr As String 
With Range("D3:D3000") 
    Range("D3").Select 
    Set LastCell = .Cells(.Cells.Count) 
End With 
Set FoundCell = Range("D1:D3000").Find(What:=" Total", After:=LastCell, LookIn:=xlValues, LookAt:=xlPart, _ 
    SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) 
If Not FoundCell Is Nothing Then 
    FirstAddr = FoundCell.Address 
End If 
Do Until FoundCell Is Nothing 
    Set FoundCell = Range("D1:D3000").FindNext(After:=FoundCell) 

    COLUMNS("D:D").Select 
    Selection.Find(What:=" Total", After:=ActiveCell, LookIn:=xlValues, _ 
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Activate 
    ActiveCell.Replace What:="Total", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _ 
    SearchFormat:=False, ReplaceFormat:=False 
    ActiveCell.Rows("1:1").EntireRow.Select 
    ActiveCell.Activate 
    Application.CutCopyMode = False 
    Selection.Insert Shift:=xlDown 
    ActiveCell.Offset(3, 0).Rows("1:1").EntireRow.Select 
    Selection.Insert Shift:=xlDown 
    . 
    . 
    . 
    If FoundCell.Address = FirstAddr Then 
     Exit Do 
    End If 
Loop 
Range("A1").Select 
End Sub 
+0

哪行代码给你错误? –

回答

0

有两个步骤来创建一个对象变量。首先你必须声明对象变量。 发生此错误是因为您没有正确设置对象,因此如果您有编程经验,它与空引用异常完全相同。 我运行了你的代码,它似乎根本没有做任何事情! 甚至没有错误!所以我认为你的错误一定是因为你的代码中的其他地方。 任何方式这行代替活动工作表中的任何总计:

Cells.Replace What:=" Total", Replacement:="", LookAt:=xlPart, _ 
     SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ 
     ReplaceFormat:=False