Connecting Excel to PostgreSQL via VBA

vivid picture vivid · Nov 5, 2012 · Viewed 33.9k times · Source

Is it possible to make query like SELECT from VBA in Excel, so I can query a PostgreSQL DB from Excel?

If is possible please explain me how to connect to the database. I was looking in Google but found no results.

Answer

subZero picture subZero · Nov 5, 2012

Here's some code can use as reference. Hope it helps.

Sub SelectBasic()

        Dim objDb_con
        Dim strSomeValue As String

        Set objDb_con = CreateObject("ADODB.Connection")
        Set Rsdatatype = CreateObject("ADODB.RecordSet")

        glbConnString = Trim(ActiveSheet.Range("B1").Value)
        //Connection string format:Driver={PostgreSQL Unicode};Database=MyDB;server=192.16*.*.**;UID=USERID;Pwd=pasword //comment it
        If glbConnString = "" Then
         MsgBox "Enter the Connection String"
        Else:

        objDb_con.Open glbConnString

        strSql = "select strSomeValue  from SOMETABLE where Something=1"
        Rsdatatype.Open strSql, objDb_con, adOpenKeyset, adLockpessimistic
        If Rsdatatype.EOF = False Then strSomeValue = Rsdatatype.Fields(0).Value
        Rsdatatype.Close

        End If
        objDb_con.Close
    End Sub