2014-04-23 31 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