对象变量或未设置块变量 - Userform Data Validation

时间:2017-05-05 09:20:11

标签: excel vba excel-vba

我正在接受

  

运行时错误' 91':对象变量或未设置块变量

关于这段特殊的代码,我无法弄清楚它有什么问题......

'Booking Number Validation
With Sheets("New Enquiries")
Dim r As Excel.Range
Set r = .Range("A:A").Find(What:=BookingNumberTextBox.Text, LookAt:=xlWhole, MatchCase:=False)

    If r = BookingNumberTextBox.Text Then
        MsgBox ("Booking Number already exists.")
        Call UserForm_Initialize
    Else
        MsgBox ("Enquiry has been added.")
    End If

End With

我收到了If r = BookingNumberTextBox.Text Then

行的错误

这一点是通过用户表单添加数据时的注意事项,

  1. 如果预订编号已存在,请告知用户然后初始化用户表单
  2. 如果不存在,请添加数据并确认输入。
  3. 编辑:根据YowE3K的回答,我修改了他的代码并提出了以下内容;

    'Booking Number Validation
    With Sheets("New Enquiries")
        Dim r As Excel.Range
        Set r = .Range("A:A").Find(What:=BookingNumberTextBox.Text, LookAt:=xlWhole, MatchCase:=False)
    
        If r Is Nothing Then
            MsgBox "Enquiry has been added."
        Else
            If r.Value = BookingNumberTextBox.Text Then
                MsgBox "Booking Number already exists."
                Call UserForm_Initialize
            End If
        End If
    End With
    

1 个答案:

答案 0 :(得分:4)

在尝试使用范围之前,您没有检查该值是否已存在:

'Booking Number Validation
With Sheets("New Enquiries")
    Dim r As Excel.Range
    Set r = .Range("A:A").Find(What:=BookingNumberTextBox.Text, LookAt:=xlWhole, MatchCase:=False)

    If r Is Nothing Then
        'Find was not successful - do whatever you want in that situation
        '...
        '...
    Else
        'Find was successful
        If r.Value = BookingNumberTextBox.Text Then
            MsgBox "Booking Number already exists."
            Call UserForm_Initialize
        Else
            'You shouldn't ever reach this spot because you were searching
            'for BookingNumberTextBox.Text, so r.Value should be equal to it
            MsgBox "Enquiry has been added."
        End If
    End If

End With

根据OP的修订代码,最终解决方案可以简化为:

'Booking Number Validation
With Sheets("New Enquiries")
    Dim r As Excel.Range
    Set r = .Range("A:A").Find(What:=BookingNumberTextBox.Text, LookAt:=xlWhole, MatchCase:=False)

    If r Is Nothing Then
        MsgBox "Enquiry has been added."
    Else
        MsgBox "Booking Number already exists."
        Call UserForm_Initialize
    End If
End With