简体   繁体   中英

Populate combobox access 2007 using vba with postgresql table

I'm trying to populate a combobox with records from a table filtered by a parent combobox. The table I want to filter is called muni and parent table is called prov. They are related by a common field (muni has a field called gid_prov that contains prov gid for each record) First combobox stores the prov gid and shows the prov name. Both tables are in a database from postgresql connected to access by an DSN file using ODBC. I have tried many options, and none is correct. First I tried a simple option. This code is useless now

Private Sub PROV_Change()
   MUNI.RowSourceType = "Table/Query"
   MUNI.RowSource = "select *  from memoria.muni  where gid_provs =" & PROV
   MUNI.Requery
   MUNI.SetFocus
   MUNI.Text = ""

   End Sub

PROV is the name of the parent combobox that stores the prov gid. And MUNI the combobox I want to populate. Other option I tried was creating a query with an sql statement, this is the code right now, i tried with the OpenRecordsetOutput, but is not working. I can access the database and get the fields, but I can't populate the combobox MUNI

     Private Sub PROV_Change()
    Dim oDb As DAO.Database
    Dim oRs As DAO.Recordset
    dbconnect = "ODBC;DRIVER=PostgreSQL ANSI;UID=***;PWD=***;PORT=5432;SERVER=127...;DATABASE=memoria_historica;DSN=C:\Users\***"
    Set oDb = OpenDatabase("", False, False, dbconnect)
Dim sql As String
sql = "select gid,nombre  from memoria.municipios m where m.gid_provs =" & PROV & "order by m.nombre;"
Set oRs = oDb.OpenRecordset(sql, dbOpenSnapshot, dbSQLPassThrough)
Me.muni2.RowSource = ""
If oRs.RecordCount > 0 Then
With oRs
.MoveFirst
.MoveNext

Do While Not .EOF
                    muni2.AddItem .Fields("nombre").Value

                    .MoveNext
Loop
End With
End Sub

Worked fine tih the support of @Thaippo. Thanks

You can you DAO library.

You could you DAO. Database and DAO. Recordset like:

Dim oDb as DAO.Database
Dim oRs as DAO.Recordset

Your second block of codes could do the work.

Set oDb = OpenDatabase("", False, False, dbconnect)
Dim sql As String
sql = "select m.nombre  from memoria.muni 
m,memoria.prov p where st_within(m.the_geom,p.the_geom) and p.gid =" & PROV ";"

Set oRs = oDb.Openrecordset(sql) 

If oRs.Recordcount > 1 Theb
With oRs
.Movelast
.Movefirst

Do while not.EOF
                    PROV.Additem . Fields("nameOfFieldsYouNeed"). Value
                    .Movenext
Loop
End With

End if

And it's would be a good idea to clear the combox box before adding new items in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM