2012-02-27 78 views
2

這個宏只需點擊一個按鈕即可運行。我收到一個錯誤。VBA調試問題

運行時錯誤「91」: 對象變量或帶塊變量未設置

我點擊調試,它使我這個突出的區域。

Selection.Find(What:=DateString, After:=ActiveCell, LookIn:=xlFormulas, _ 
     LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
     MatchCase:=False).Activate 

這裏是全功能

Function GetBalance(Month As Integer) As Currency 
'This function is called by the Calculate_Balance subroutine. It 
'finds the appropriate month's balance on an employee sheet and sends 
'it back to the calling routine. 

Dim DateString As String 
Dim RangeString As String 
Dim Balance 
Dim BalDate As Date 
Dim strCurrMonth As String 
Dim strCurrYear As String 
Dim strFirstDayCurrMonth As String 

    strCurrMonth = CStr(DatePart("m", Date)) 
    strCurrYear = CStr(DatePart("yyyy", Date)) 
    strFirstDayCurrMonth = strCurrMonth & "/1/" & strCurrYear 
    dtmFirstDayCurrMonth = CDate(strFirstDayCurrMonth) 

    DateString = Month & "/1/" 

    Columns("A:A").Select 
    Range("A6").Activate 
    Selection.Find(What:=DateString, After:=ActiveCell, LookIn:=xlFormulas, _ 
     LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
     MatchCase:=False).Activate 

    CurrRow = ActiveCell.Row 
    BalanceRow = CurrRow - 1 'Move up 1 row to get last balance for this month 

    RangeStr = "E" & BalanceRow 
    DateRangeStr = "A" & BalanceRow 

    BalDate = Range(DateRangeStr).Value 
    If BalDate <= dtmFirstDayCurrMonth Then 
     Balance = Range(RangeStr).Value 
    Else 
     Balance = 0 
    End If 

    GetBalance = Balance 

End Function 

回答

4

的查找()函數返回一個Range對象,以便與您的代碼,如果沒有找到,你會因爲它不能「激活」沒什麼得到一個錯誤。更改代碼類似於:

Dim rng As Range 

Set rng = Selection.Find(What:=DateString, After:=ActiveCell, LookIn:=xlFormulas, SearchDirection:=xlNext, MatchCase:=False) 

If Not (rng Is Nothing) Then 
    rng.Activate 
End If 
+0

我試過這個,我不再收到一個錯誤。然而,宏運行的每一行...... – PlatiNUM 2012-02-27 16:38:16

+0

如果你對它感到滿意,請接受答案,因爲它似乎解決了你的原始問題。 – markblandford 2012-02-27 16:57:09

+0

錯誤的問題已經解決,但仍然不正確。 – PlatiNUM 2012-02-27 17:58:42