Sunday, August 12, 2007

Detecting duplicate values (Excel VBA)

Check presence of values in a column/range using Excel VBA

Most often a programmer would be given a job of Insert/Update scenarion in EXcel. That is, Insert a new row if a specific value does not exist; if it does then update some. So the process is to check for existence of a specific value

Here is a generic function ;

Sub CheckForExistence()

myVal = "Sample"
myRange = "A:A"
If Check_Val_Existence(myVal, myRange) = True Then
MsgBox "Value exists"
End If
End Sub

This used the Find Method. This method finds specific information in a range, and returns a Range object that represents the first cell where that information is found. Returns Nothing if no match is found.


Function Check_Val_Existence(ByVal sText, ByVal sRange) As Boolean

Dim rFnd As Range
Dim sText As String

Set rFnd = ActiveSheet.Range(sRange).Find(What:=sText, LookAt:=xlPart)
If Not rFnd Is Nothing Then
Check_Val_Existence = True
Else
Check_Val_Existence = False
End If

End Function

16 comments:

  1. Code doesn't work, Stext is declared twice

    ReplyDelete
  2. Thanks Pavel

    It should have been

    Function Check_Val_Existence(ByVal sText, ByVal sRange) As Boolean

    Dim rFnd As Range

    Set rFnd = ActiveSheet.Range(sRange).Find(What:=sText, LookAt:=xlPart)
    If Not rFnd Is Nothing Then
    Check_Val_Existence = True
    Else
    Check_Val_Existence = False
    End If

    End Function

    ReplyDelete
  3. Hi,

    I need a help in Excel. I have created an excel file with 3 input boxes. That means, once I press Button an input box will pop-up asking me to enter the value, and the value I enter will be entered in Column 'B' 'C' and 'D' with respective input boxes. Now I want that before entering the value in respective column, macro should search if there is a duplicate value in that column or not. If any exist it should prompt that a duplicate value already exist in the column.

    Could you please help me with this.

    Looking forward to hear from you.
    Thanks

    Puneet Jha

    ReplyDelete
  4. Hi Pavel and Shasur,

    Thanks a lot for the help. But still my problem is not solved. For your kind reference I am copying below the code I am using.
    It may not be the correct code as I am at a very initial level of learning VB.

    Public Sub Submit_Click()

    Range("C:C").Find(What:="", LookAt:=xlWhole).Select
    ActiveCell.Value = InputBox("Please enter the word you want to enter in column C")
    Range("C1:C65536").FindNext

    Range("D:D").Find(What:="", LookAt:=xlWhole).Select
    Range("D:D").Find(What:="", LookAt:=xlWhole).Select
    ActiveCell.Value = InputBox("Please enter the word you want to enter in column D")
    Range("D1:D65536").FindNext

    Range("E:E").Find(What:="", LookAt:=xlWhole).Select
    Range("E:E").Find(What:="", LookAt:=xlWhole).Select
    ActiveCell.Value = InputBox("Please enter the word you want to enter in column E")
    Range("E1:E65536").FindNext
    ActiveWorkbook.Save

    End Sub

    Now actually I want, after user enters a word he/she wants to enter in column C, D and E, the code should search in the column whether the word entered by user already exist in the column or not. If the word exist, code
    should give a message that "The word you want to enter already exist in "" column" after showing this message the code should take user to the cell and select the cell were the word entered by user already exist. And if the word does not exist code should take user to the first empty cell in the column and allow user to enter word in the cell.

    Can you please help me with this.

    Looking forward to your response.

    Warm Regards
    Puneet Jha

    ReplyDelete
  5. Anonymous10:53 PM

    Hi Punjeet!
    There is a MUCH simpler way to acheive what you're doing! Here's a neat little trick to do this:-
    It's easier to use column NUMBERS instead of LETTERS. The best way to do this, is to reference them as "Cells" instead of as "Range" coordinates. (meaning, instead of writing:
    ' Range("C1").Value
    you simply write:
    ' Cells(3, 1).Value
    or even better, you can replace these numbers with variables:
    ' Cells(ColNum, RowNum).Value
    Now, the code in your Submit_Click() routine will be much simpler, because the bulk of it will be done in one simple sub-routine, that can be reused witout having to re-write it! And here it is:
    Sub AddNonDuplicate(ByVal ColNum
    As Integer, ByVal MyValue
    As String)

    Dim RowNum As Integer
    RowNum = 1
    'Starting in the
    'first row Do
    If Cells(CelNum, RowNum).Value = MyValue Then
    '(If the value of any row in your column is the same as the one you are trying to add, it is a duplicate, and should say so and exit:)MsgBox MyValue & " already exists in this column!"
    Exit Sub
    End If
    RowNum = RowNum + 1
    'check the next row down Loop Until Cells(ColNum, RowNum).Value = "" 'stop when you find the first blank

    'Now it has checked every non-blank cell, and hasn't found a duplicate, so if it has got this far, it can be added to the blank cell it stopped on: Cells(ColNum, RowNum).Value = MyValue
    End Sub
    'Now here's how simple your Submit_Click() routine becomes: Public Sub Submit_Click()
    Dim InputValue As String
    'Variable to hold input value
    InputValue = InputBox("Please enter the word you want to enter in column C")
    Call AddNonDuplicate(3, InputValue)
    'Column C is actually column 3 InputValue = InputBox("Please enter the word you want to enter in column D")
    Call AddNonDuplicate(4, InputValue)
    'Column D is actually column 4 InputValue = InputBox("Please enter the word you want to enter in column E")
    Call AddNonDuplicate(5, InputValue)
    'Column E is actually column 5 ActiveWorkbook.Save
    End Sub
    Hope this helps!
    -Belial9. ;)

    ReplyDelete
  6. I see that you all are very patient with new VBA users so I thought I would ask for help.

    I am attempting to make a UserForm to input data into four fields.
    *Tank1Rec, Qty1R,- these go into worksheet named Received
    *Tank1Ship, Qty1S - thes go into worksheet named shipped

    I wish to input data from the "cainmonth***" calendar ActiveX command so that the data goes from the input form to Column A when I click on my command button "UPDATE"

    In column B I wish to put the quantity inputted on the form.

    I put column Headers (Tank1RDate/Qty1R)

    The worksheet name is called received.

    I hope this is enough information.

    ReplyDelete
  7. Anonymous8:28 AM

    I was wondering if this was still active: if so i have a dilemna-
    Greetings friends,
    I have limited excel knowledge and experience, yet despite that, through the painstaking process of searching online forums such as this one, i have managed to create a "Employee Punch in/out" userform. So far i am happy with it.

    Here is how it works:
    A employee types in his Last Name in textbox1, then his First in textbox2.
    Then the employee clicks the command Button

    this causes his last name, first name, date and tme to populate an excel spread sheet by row-
    (i've managed to create and attach the VBA coding for time and date to automatically generate for this and it works Great)

    Here is my problem:
    for the employee to punch "out", i need code for excell to identify the employee by his last name in column " a" and first name in column "b" and not simply populate another row that way the OUT time populates in the same row as the in time.

    here is my code:
    Private Sub CommandButton1_Click()
    Dim iRow As Long
    Dim ws As Worksheet
    Set ws = Worksheets("sheet1")

    'find first empty row in database
    iRow = ws.Cells(Rows.Count, 1) _
    .End(xlUp).Offset(1, 0).Row

    'check for a part number
    If Trim(Me.TextBox1.Value) = "" Then
    Me.TextBox1.SetFocus
    MsgBox "Please enter Required Information"
    Exit Sub
    End If
    If Trim(Me.TextBox2.Value) = "" Then
    Me.TextBox2.SetFocus
    MsgBox "Please enter Required Information"
    Exit Sub
    End If

    'copy the data to the database
    ws.Cells(iRow, 1).Value = Me.TextBox1.Value
    ws.Cells(iRow, 2).Value = Me.TextBox2.Value

    ws.Cells(iRow, 3).Value = Date
    ws.Cells(iRow, 4).Value = Time()

    'clear the data
    Me.TextBox1.Value = ""
    Me.TextBox2.Value = ""





    End Sub

    Private Sub CommandButton2_Click()
    Dim iRow As Long
    Dim ws As Worksheet
    Set ws = Worksheets("sheet1")



    'find first empty row in database
    iRow = ws.Cells(Rows.Count, 1) _
    .End(xlUp).Offset(0).Row


    If Trim(Me.TextBox1.Value) = "" Then
    Me.TextBox1.SetFocus
    MsgBox "Please enter Required Information"
    Exit Sub
    End If
    If Trim(Me.TextBox2.Value) = "" Then
    Me.TextBox2.SetFocus
    MsgBox "Please enter Required Information"
    Exit Sub
    End If

    'clear the data
    Me.TextBox1.Value = ""
    Me.TextBox2.Value = ""


    ws.Cells(iRow, 5).Value = Time()
    End Sub

    ReplyDelete
  8. Anonymous12:23 AM

    I would rather Suggest to have a listbox instead of Textboxes because the Text entered need not be the exact match of what is available in Excel spreadsheet. For example, Schmidt, Shmidt, Schmid etc are ...

    So you can list all the first and last name in the Listbox and have the user select it.

    ReplyDelete
    Replies
    1. can u help me for a simple vba code please

      Delete
  9. duplicate item number from every store like example-:
    Store Item
    4702 1158
    4706 1158
    4702 56666
    4717 1158
    4750 56666
    4712 1158
    4713 1158
    4716 56666
    4719 1158
    4720 56666
    i want the duplicate item number along with the sotre number in excel sheet by the vba code how can i do it please help...

    ReplyDelete
  10. how can i get duplicate item number from a multiple data which is holding item number along with stroe number by vba code like-

    store Item
    4702 1158
    4703 1158
    4706 1158
    4717 1158

    please help me out there is confusion

    ReplyDelete
  11. I'm trying to do vb code for my work schedule to make sure 2 names are not in the same row. Any ideas?

    Sample excel format

    Name1 Name2 Name3 Name4
    Name1 Name1 Name3 Name4

    //want to avoid 2 Name1's

    ReplyDelete
  12. Anonymous11:26 PM

    You can use CountIf to identify the duplicates. Since you are checking this across multiple columns .. you need to write a loop to iterate rows and then iterate columns..

    ReplyDelete
    Replies
    1. may u please write a code over here i m so confused

      Delete
  13. please can u write a code for the same example like
    Store Item
    4702 1158
    4706 1158
    4702 56666
    4717 1158
    4750 56666
    4712 1158
    4713 1158
    4716 56666
    4719 1158
    4720 56666

    here i need the every item number which is common in every store in sheet 2 by vba code please help

    ReplyDelete
  14. Anonymous8:03 AM

    'You can copy paste my whole reply. EXAMPLE as below
    If Application.CountIf(Range("E:E"), Textbox1.Value) > 0 Then
    msgbox ("Duplicate found")

    ReplyDelete

StumbleUpon
Share on Facebook
Related Posts Plugin for WordPress, Blogger...

Visual Basic for Applications (VBA) Forum (recent threads)

CodeKeep VBA Feed

Visual Studio Tools for Office Forum (recent threads)

Download Windows Live Toolbar and personalize your Web experience! Add custom buttons to get the information you care about most.

Office Business Applications (OBA) Team Blog

MSDN Code Gallery Published Resources For Tag VSTO

microsoft.public.vsnet.vstools.office Google Group