检查工作表列中是否已存在字符串

时间:2015-12-11 21:55:39

标签: vba excel-vba userform excel

我有一个用户表单,它应该验证新记录条目以避免重复数据。我使用Chip Pearson的FindAll(http://www.cpearson.com/excel/findall.aspx)方法阻止用户输入记录 如果工作表列中已存在匹配的记录,则命名(Column" D")。如果FindAll确定匹配的字符串 已经在列中,我想禁用保存按钮,更改包含重复记录的文本框的背景 字符串,并显示一个信息标签,要求用户更改违规记录条目。我遇到的问题是FindAll是 尽管我已确认目标中存在与新记录条目匹配的字符串,但仍未按预期工作 工作表专栏。有人可以向我解释为什么我的FindAllMatches子程序没有按预期工作:

Const sDefaultRecordMessage As String = "Enter record name."

Private Sub tbRecord_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    'Calls the FindAllMatches routine as user types text in the textbox
    Call FindAllMatches
End Sub

Private Sub tbRecord_Enter()
    With Me.tbRecord
        If .Text = sDefaultRecordMessage  Then .Text = vbNullString
    End With
End Sub

Private Sub tbRecord_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    With Me.tbRecord
        If .Text = vbNullString Then .Text = sDefaultRecordMessage 
    End With

    Call FindAllMatches
End Sub

Private Sub FindAllMatches()
    Dim SearchRange As Range
    Dim FindWhat As Variant

    FindWhat = Trim(Me.tbRecord.Value)

    Set SearchRange = ActiveSheet.Range("D3").End(xlDown)

    'Calls Chip Pearson's FindAll function
    Set FoundCells = FindAll(SearchRange:=SearchRange, _
                            FindWhat:=FindWhat, _
                            LookIn:=xlValues, _
                            LookAt:=xlPart, _
                            SearchOrder:=xlByColumns, _
                            MatchCase:=True, _
                            BeginsWith:=vbNullString, _
                            EndsWith:=vbNullString, _
                            BeginEndCompare:=vbTextCompare)
    If FoundCells Is Nothing Or Len(Me.tbRecord.Value) = 0 Then
        Me.lblDuplicateMessage.Visible = False
        Me.cbSaveRecord.Enabled = True
        Me.tbRecord.BackColor = &H80000005
    Else
        Me.lblDuplicateMessage.ForeColor = RGB(255, 0, 0)
        Me.lblDuplicateMessage.Visible = True
        Me.tbRecord.BackColor = RGB(255, 204, 204)
        Me.cbSaveRecord.Enabled = False
    End If
End Sub

我做错了什么?

1 个答案:

答案 0 :(得分:1)

ActiveSheet.Range("D3").End(xlDown)将搜索范围设置为单个单元格...

但是,由于您实际上不需要计算出现次数,因此在整个列上使用Match()会更快/更容易:

If Not IsError(Application.Match(Trim(Me.tbRecord.Value), _
                                 ActiveSheet.Range("D:D"), 0)) Then
    'have an existing match in ColD
End If