2015-12-11 126 views
0

我有一個用戶表單應該驗證新記錄條目以避免重複數據。如果工作表列(列「D」)中已存在匹配記錄,則我使用Chip Pearson的FindAll(http://www.cpearson.com/excel/findall.aspx)方法來防止用戶輸入記錄名稱 。如果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

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 
+0

我想從搜索中排除單元格「D1」和「D2」,因爲它們分別包含一個標頭和一排宏按鈕。您的解決方案搜索所有列「D」。 – ScoobyDoo2015

+0

如果它們是標題,它們是否可能包含正在搜索的值?但你可以使用ActiveSheet.Range(ActiveSheet.Range(「D3」),ActiveSheet.Range(「D3」).End(xlDown)),而不是ActiveSheet.Range(「D:D」) –

+0

@Bob Phillips I同意這不太可能,但我想盡管排除這些單元格。我會嘗試你的解決方案。 – ScoobyDoo2015

相關問題