如果其他人没有被认出

时间:2018-08-29 17:39:48

标签: excel vba if-statement

我有一个用户可以输入数字的表格,并且我想让我的宏检查特定列表中是否存在该数字,以便进行某些处理。这是我的操作方式:

Private Sub CommandButton3_Click()
 Dim number As Integer, i As Integer
 For i = 10 To 10020
     If TextBox1.Value = Sheet1.Cells(i, 2).Value Then
         number = TextBox1.Value
     End If
 Next i
     MsgBox "A dica número " & TextBox1.Value & " não consta na lista.", vbOKOnly, "Dica não encontrada!"
     Exit Sub

 'Do the rest of the code here
End Sub

问题是:无论我输入什么数字,总是会出现消息框。从未读取number = TextBox1.Value。 我尝试手动检查带有消息框的特定输入的值是否相同,即使它们相同,也从未访问过If / Else。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

首先,在文本框中输入的数字将被视为字符串而不是数字。因此,您需要将其转换为数字,然后尝试执行此操作...

If Val(Me.TextBox1.Value) = Sheet1.Cells(i, 2).Value Then

第二件事,您无需遍历单元格即可检查是否在特定范围内找到了在TextBox中输入的数字。您可以利用CountIf函数来执行以下操作。

If Application.CountIf(Sheet1.Range("B10:B10020"), Me.TextBox1.Value) > 0 Then
    MsgBox "Found"
Else
    MsgBox "Not Found"
End If

答案 1 :(得分:0)

将代码更改为

Option Explicit

Private Sub TextBox1_Change()

End Sub
Private Sub CommandButton3_Click()

Dim number As Integer, i As Integer

    For i = 10 To 10020
        If TextBox1.Value = Tabelle1.Cells(i, 2).Text Then
            number = TextBox1.Value
            Exit Sub
        End If
    Next i

    MsgBox "A dica número " & TextBox1.Value & " não consta na lista.", vbOKOnly, "Dica não encontrada!"

    Exit Sub

    'Do the rest of the code here
End Sub

更新,但这也许是您真正想要的

Private Sub CommandButton3_Click()
Dim number As Integer
Dim rg As Range
    With Sheet1
        Set rg = .Range(.Cells(10, 2), .Cells(10020, 2))
    End With
    Dim rgRes As Range
    Set rgRes = rg.Find(TextBox1.Value)
    If Not (rgRes Is Nothing) Then
        number = TextBox1.Value
    Else
        MsgBox "A dica número " & TextBox1.Value & " não consta na lista.", vbOKOnly, "Dica não encontrada!"
    End If

End Sub