VBAdebugging问题

这个macros运行在一个button上。 我收到一个错误。

运行时错误“91”:对象variables或块variables未设置

我点击debugging,它导致我到这个突出显示的区域。

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

这是整个function

 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 

如果找不到任何东西,Find()函数会返回一个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