我正在尝试创建一个功能问题。
该功能应该执行以下操作: - 询问价值观 - 如果B:B列中存在或不存在该值,则返回True或False。
这就是我到目前为止......
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim Ret As Boolean
Dim FindText As String
If KeyCode = 13 Then
With Sheets("Dados")
Columns("B:B").Select
FindText = TextBox1.Text
Ret = Selection.Find(What:=FindText, After:=.Cells(1, 1), LookIn:=xlValues, LookAt _
:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase _
:=False, SearchFormat:=False).Activate
MsgBox "Hy " & FindText & " > " & Ret
If FindText Is Nothing Then Exit Sub
End With
End If End Sub
值为true时效果很好,但如果值为false,则为runtime error 91 - Object variable or With block variable not set
:(
答案 0 :(得分:0)
FindText是一个字符串变量而不是一个Object变量。只有对象可以设置为或具有值Null。所以当执行False时。它正在寻找一个Object,因为它没有设置它会引发错误。
您甚至不需要代码行,因为它会在进入选择后计算。您需要在进行检查之前验证数据,因此请尝试这样做。
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim Ret As Boolean
Dim FindText As String
If Len(TextBox1.Text & vbNullString) = 0 Then Exit Sub
If KeyCode = 13 Then
With Sheets("Dados")
Columns("B:B").Select
FindText = TextBox1.Text
Ret = Selection.Find(What:=FindText, _
After:=.Cells(1, 1), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False).Activate
MsgBox "Hy " & FindText & " > " & Ret
End With
End If
End Sub
答案 1 :(得分:-1)
首先关闭stop using .select
。其次,您错过了Columns
之前的一段时间来引用您的With
...
Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim Ret As Boolean
Dim FindText As String
If KeyCode = 13 Then
If TextBox1.Text = "" Then Exit Sub
FindText = TextBox1.Text
With Sheets("Dados")
If .Columns("B:B").Find(What:=FindText, After:=.Cells(1, 1), LookIn:=xlValues, LookAt_
:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase_
:=False, SearchFormat:=False) is Nothing Then
Ret = False
Else
Ret = True
End If
End With
MsgBox "Hy " & FindText & " > " & Ret
End If
End Sub