vba运行时错误91使用搜索和更新命令

时间:2017-02-19 19:29:40

标签: vba

我正在使用代码通过userform更新数据库中的数据。它的第一部分即搜索数据工作正常,但第二部分即更新某些时候它工作正常但有时它给运行时错误91

需要帮助

Private Sub cmd_Update_Click()
Application.DisplayAlerts = False
Dim ws As Worksheet
'check for a Name number
If Trim(Me.TextBox_Search_Data.Value) = "" Then
Me.TextBox_Search_Data.SetFocus
MsgBox "Please fill the data in search box"
Exit Sub
End If
Set ws = Worksheets("Employee Data")
With ws
r.Value = Me.TextBox_Search_Data.Value
r.Offset(, 1).Value = Me.TextBox_EmployeeName.Value
r.Offset(, 2).Value = Me.TextBox_FatherHusbandName.Value
r.Offset(, 3).Value = Me.ComboBox_Designation.Value
r.Offset(, 4).Value = Me.ComboBox_Category.Value


Me.TextBox_Search_Data.SetFocus
MsgBox "Data Updated Sucessfully"

'clear the data
Me.TextBox_EmployeeNumber.Value = ""
Me.TextBox_EmployeeName.Value = ""
Me.TextBox_FatherHusbandName.Value = ""
Me.ComboBox_Designation.Value = ""
Me.ComboBox_Category.Value = ""


End With
End Sub

1 个答案:

答案 0 :(得分:0)

看起来工作表可能没有正确设置,因此它无法使用该对象进行更新。请参阅以下修改后的代码:

Private Sub cmd_Update_Click()

    Application.DisplayAlerts = False

    Dim ws As Worksheet
    'check for a Name number
    If Trim(Me.TextBox_Search_Data.Value) = "" Then
        Me.TextBox_Search_Data.SetFocus
        MsgBox "Please fill the data in search box"
        Exit Sub
    End If

    ' Change ThisWorkbook to a different workbook variable as needed.

    Set ws = ThisWorkbook.Worksheets("Employee Data")  
    If Not ws Is Nothing Then
            If not r is Nothing Then
                With r
                    .Value = Me.TextBox_Search_Data.Value
                    .Offset(, 1).Value = Me.TextBox_EmployeeName.Value
                    .Offset(, 2).Value = Me.TextBox_FatherHusbandName.Value
                    .Offset(, 3).Value = Me.ComboBox_Designation.Value
                    .Offset(, 4).Value = Me.ComboBox_Category.Value
                End With
           Else
               'This will run if r is not set to a range.
           End If
    Else
        'This will occur if the sheet isn't set properly.
    End If

    Me.TextBox_Search_Data.SetFocus
    MsgBox "Data Updated Sucessfully"

    'clear the data
    Me.TextBox_EmployeeNumber.Value = ""
    Me.TextBox_EmployeeName.Value = ""
    Me.TextBox_FatherHusbandName.Value = ""
    Me.ComboBox_Designation.Value = ""
    Me.ComboBox_Category.Value = ""

End Sub