excel vba中的错误91

时间:2018-01-26 14:16:23

标签: vba excel-vba excel

Private Sub lstLookup_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
'declare the variables
    Dim cPayroll As String
    Dim I As Integer
    Dim findvalue
    'error block
    On Error GoTo errHandler:
    'get the select value from the listbox
    For I = 0 To lstLookup.ListCount - 1
        If lstLookup.Selected(I) = True Then
            cPayroll = lstLookup.List(I, 1)
        End If
    Next I
    'find the payroll number
    Set findvalue = Sheet2.Range("F:F").Find(What:=cPayroll, LookIn:=xlValues).Offset(0, -3)
    'add the database values to the userform
    cNum = 21
    For X = 1 To cNum
        Me.Controls("Reg" & X).Value = findvalue
        Set findvalue = findvalue.Offset(0, 1)
    Next
    'disable adding
    Me.cmdAdd.Enabled = False
    Me.cmdEdit.Enabled = True
    'error block
    On Error GoTo 0
    Exit Sub
errHandler::
    MsgBox "An Error has Occurred  " & vbCrLf & "The error number is:  " _
           & Err.Number & vbCrLf & Err.Description & vbCrLf & _
           "Please notify the administrator"
End Sub

1 个答案:

答案 0 :(得分:2)

在您的问题中,请确保始终提及错误的位置。例如,你在这条线上得到它:

Set findvalue = Sheet2.Range("F:F").Find(What:=cPayroll, LookIn:=xlValues).Offset(0, -3)

这是因为您正在使用Offset()滥用.Find()功能。例如,在使用Offset()

之前,尝试查看可以找到的内容
Sub TestMe()
    Dim findValue
    If Not Worksheets(2).Range("F:F").Find(What:=78, LookIn:=xlValues) Is Nothing Then
        Set findValue = Worksheets(2).Range("F:F").Find(What:=78, _
                                                        LookIn:=xlValues).Offset(1, 1)
    End If
End Sub