Consulting

Results 1 to 6 of 6

Thread: Select unique record SQL-VBA

  1. #1

    Select unique record SQL-VBA

    Thanks in advance for your help.
    I have an Access database and the record is like this:

    Date Country Type Index
    1.1 Canada A
    2.1 Canada A
    3.1 Canada A
    4.1 Canada A
    5.1 Canada A
    6.1 Canada A
    1.1 US A
    2.1 US A
    3.1 US A
    4.1 US A
    5.1 US A
    6.1 US A
    ......
    How can I select the unique country names from the database, If the select clause is correct as following, and I would like to fill an array with the country name, the codes are as following, but there is problem with "varArray(i) = rec("Country")"

    strSELECT = "SELECT DISTINCT Country"
    strFROM = " FROM tblIndex "
    strSQL = strSELECT & strFROM
    Set rec = db.OpenRecordset(strSQL, dbOpenDynaset)
    rec.MoveLast
    rec.MoveFirst

    ReDim varArray(1 To rec.RecordCount)

    i = 1
    Do While Not rec.EOF
    varArray(i) = rec("Country")
    rec.MoveNext
    i = i + 1
    Loop

    Can anyone give me some advice?

  2. #2
    Banned VBAX Contributor Cosmos75's Avatar
    Joined
    May 2004
    Location
    Alabama, USA
    Posts
    118
    Location
    What exactly is the problem you are having? Are you generating an error? If so, what error is it?

    The code itself looks OK to me. I would make slight changes
        Dim db As DAO.Database
        Dim rec As DAO.Recordset
        strSELECT = "SELECT DISTINCT Country "
        strFROM = "FROM tblIndex;"
        strSQL = strSELECT & strFROM
        Set db = CurrentDb()
        Set rec = db.OpenRecordset(strSQL, dbOpenSnapshot)
        rec.MoveLast
        rec.MoveFirst
        Debug.Print rec.RecordCount
        ReDim varArray(1 To rec.RecordCount)
    
        i = 1
        Do While Not rec.EOF
            varArray(i) = rec("Country")
            rec.MoveNext
            i = i + 1
        Loop
    
        rec.Close
        db.Close
    Just a tip, you may want to use when posting VBA code in a thread.

  3. #3
    with a million thanks, I changed my code into yours and it works!

  4. #4
    Banned VBAX Contributor Cosmos75's Avatar
    Joined
    May 2004
    Location
    Alabama, USA
    Posts
    118
    Location
    Glad it worked for you!

  5. #5
    VBAX Newbie
    Joined
    Mar 2007
    Posts
    1
    Location
    Next time please remember to put ";" at the end of any SQL statement.
    I think it should be the main reason your code not working.

  6. #6
    Moderator VBAX Master geekgirlau's Avatar
    Joined
    Aug 2004
    Location
    Melbourne, Australia
    Posts
    1,464
    Location
    Actually I never put the ";" at the end - the SQL statement always works fine

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •