通过VBA连接Excel到PostgreSQL

有没有可能在Excel中使用VBA查询SELECT ,所以我可以从Excel中查询PostgreSQL数据库?

如果可能的话请解释我如何连接到数据库。 我正在看谷歌,但没有find结果。

在PostgreSQL中创build一个表或者视图来描述你想要的数据。

使用来自VBA的ODBC或ADO连接来连接到PostgreSQL。 如果使用ODBC,则需要通过odbcad32.exe创buildDSN,然后在VB中使用DSN,直接连接并不容易。

看到:

使用Oracle的更好的书面示例 ,但原则是相同的 – ODBC / ADO。

这里有一些代码可以作为参考。 希望能帮助到你。

 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 

即使对于64位Windows,Excel VBA也需要32位ODBC驱动程序 。

通过%windir%\SysWOW64\odbcad32.exe创build一个DSN。 确实,inputodbcad32.exe指向64位版本,默认情况下找不到合适的32位驱动程序。

资料来源: https : //github.com/windweller/postgresql-excel-addIn