对象variables或未设置块variables – 用户表单数据validation

我得到了

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

在这个特定的代码位,我不能解决它有什么问题…

'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. 如果不存在,则添加数据并确认input。

编辑:基于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 

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

 '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的修改后的代码,最终的解决scheme可以简化为:

 '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