2014-02-19 47 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) 
相關問題