【问题标题】:Checking If String Already Exists in Worksheet Column检查工作表列中是否已存在字符串
【发布时间】:2015-12-12 06:41:57
【问题描述】:

我有一个应该验证新记录条目以避免重复数据的用户表单。我正在使用 Chip Pearson 的 FindAll (http://www.cpearson.com/excel/findall.aspx) 方法来防止用户输入记录 如果工作表列(“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

我做错了什么?

【问题讨论】:

    标签: vba excel userform


    【解决方案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
    

    【讨论】:

    • 我想从搜索中排除单元格“D1”和“D2”,因为它们分别包含标题和宏按钮行。您的解决方案搜索所有“D”列。
    • 如果它们是标题,它们是否可能包含正在搜索的值?但是你可以只使用 ActiveSheet.Range(ActiveSheet.Range("D3"), ActiveSheet.Range("D3").End(xlDown)),而不是 ActiveSheet.Range("D:D")
    • @Bob Phillips 我同意这不太可能,但我还是想排除这些单元格。我会试试你的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    相关资源
    最近更新 更多