为什么尽管在excel工作表中有一个匹配,Application.Match函数是不是应该怎么做?

时间:2018-06-01 06:53:53

标签: excel-vba vba excel

代码如下:

Private Sub txtv_AfterUpdate()
Total_rows_Entries = Worksheets("Entries").Range("A" & Rows.Count).End(xlUp).Row

If IsError(Application.Match(txtv.Value, Worksheets("Entries").Range("A2:A" & Total_rows_Entries), 0)) = False Then
    MsgBox "This voucher number has already been used previously. Voucher numbers cannot be duplicated."
End If

End Sub

txtv.Value是一种数字类型,它是文本框值。

工作表如下所示: Worksheet

我的匹配目的是,如果工作表中已经存在多个“123”,那么它应该返回消息框,但无论我将类型更改为.Text还是{{},它都会绕过它1}}或手动将excel中的单元格类型更改为常规,文本或数字。

3 个答案:

答案 0 :(得分:2)

尝试这种广泛的比较。

If not (IsError(Application.Match(clng(txtv.Value), Worksheets("Entries").columns(1), 0)) And _
        IsError(Application.Match(cstr(txtv.Value), Worksheets("Entries").columns(1), 0))) Then
    MsgBox "This voucher number has already been used previously." & vblf & _
           "Voucher numbers cannot be duplicated."
End If

或者,尝试一些只是略微计算密集的东西但不关心它所寻找的值是字符串还是数字。

If cbool(Application.countif(Worksheets("Entries").columns(1), txtv.Value)) Then
    MsgBox "This voucher number has already been used previously." & vblf & _
           "Voucher numbers cannot be duplicated."
End If

答案 1 :(得分:2)

我要猜测这与你的列是数字而你的匹配项是字符串值有关,反之亦然。

试试这个:

Private Sub txtv_AfterUpdate()
Total_rows_Entries = Worksheets("Entries").Range("A" & Rows.Count).End(xlUp).Row

If IsError(Application.Match(INT(txtv.Value), Worksheets("Entries").Range("A2:A" & Total_rows_Entries), 0)) = False Then
    MsgBox "This voucher number has already been used previously. Voucher numbers cannot be duplicated."
End If

End Sub

或者如果是相反的尝试:

Private Sub txtv_AfterUpdate()
Total_rows_Entries = Worksheets("Entries").Range("A" & Rows.Count).End(xlUp).Row

If IsError(Application.Match(CStr(txtv.Value), Worksheets("Entries").Range("A2:A" & Total_rows_Entries), 0)) = False Then
    MsgBox "This voucher number has already been used previously. Voucher numbers cannot be duplicated."
End If

End Sub

答案 2 :(得分:0)

您可以使用Range.Find方法,该方法会查找存储为数字或文字的数字:

Private Sub txtv_AfterUpdate()
    If Not Worksheets("Entries").Range("A:A").Find(What:=txtv.Value, LookAt:=xlWhole) Is Nothing Then
        MsgBox "This voucher number has already been used previously. Voucher numbers cannot be duplicated."
    End If
End Sub