首页 > 解决方案 > 在excel vba中使用表单文本框进行重复检查

问题描述

我正在将数据从 EXCEL 用户表单存储到 Excel 工作表。我有重复检查的问题。

我在A列中的数据像这样...... 300、304、305、306、307、308、309、310等等......

例如,用户在相应的文本框中输入 306,然后消息框将显示“输入的重复数据”。

更新后我在文本框中写了以下代码,但它不起作用。任何帮助tqs...

Dim Cell As Variant
Dim Source As Range


Set Source = Worksheets("NFLAT").Range("a2:a50")

For Each Cell In Source

If Application.WorksheetFunction.CountIf(Source, Cell) > 1 Then
  MsgBox "Given number already exists"
End If

Next Cell

标签: excelvba

解决方案


不需要循环,只需检查文本框的值。如果存在 CountIf > 0(不 > 1)。

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)

    Dim rng As Range, ws As Worksheet, lastrow As Long
    Set ws = Worksheets("NFLAT")
    lastrow = ws.Range("A" & Rows.Count).End(xlUp).Row
    Set rng = ws.Range("A2:A" & lastrow)

    With Me.TextBox1
        If Application.WorksheetFunction.CountIf(rng, .value) > 0 Then
            MsgBox .value & " already exists", vbCritical, "Checked " & rng.Address
        Else
            MsgBox .value & " is OK ", vbInformation, "Checked " & rng.Address
        End If
    End With

End Sub

推荐阅读