我正在接受
运行时错误' 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
这一点是通过用户表单添加数据时的注意事项,
'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
答案 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