Link to home
Start Free TrialLog in
Avatar of Luis Diaz
Luis DiazFlag for Colombia

asked on

Excel VBA: export sql & postgresql tables

Hello experts,

The following procedure allows me to export various tables related to a ssms database.

Sub SQLQueryOut2(wsName As String, strSQL, strInitialRange, strServer)

Dim objRS
Dim SQL

Set wb = ActiveWorkbook
Set DestSh = Nothing
On Error Resume Next
Set DestSh = Sheets(wsName)
Set wsConfig = Worksheets("Config")
On Error GoTo 0

    If DestSh Is Nothing Then
        Set DestSh = wb.Sheets.Add(After:=Sheets(wb.Sheets.Count))
        DestSh.Name = wsName
        wsConfig.Select
    Else
        Sheets(wsName).Cells.ClearContents
        wsConfig.Select
    End If
    
Set objRS = CreateObject("ADODB.Recordset")


' ==> to modify
Set objConn = CreateObject("ADODB.Connection")
objConn.Open "Driver={SQL Server};" & _
"Server=" & strServer & ";" & _
"UID=user;" & _
"PWD=password;" & _
"Database=database;"


SQL = strSQL
objRS.Open SQL, objConn

On Error Resume Next
Set rs = objConn.Execute(SQL)
On Error GoTo 0
If rs Is Nothing Then
MsgBox "SQL query reported at row " & rw & "  is not properly set up unable to transfer  data."
Exit Sub
End If

 For Idx = 1 To rs.Fields.Count
        Sheets(wsName).Range(strInitialRange).Offset(0, Idx - 1) = rs.Fields(Idx - 1).Name
    Next

    Sheets(wsName).Range(strInitialRange).Offset(1).CopyFromRecordset rs

Set objRS = Nothing
Set objConn = Nothing

End Sub

Sub SQLQueryoutConfigSheet()

    Dim wsConfig As Worksheet, wsResult As Worksheet
    Set wb = ActiveWorkbook
    Set wsConfig = Worksheets("Config")
    Application.ScreenUpdating = False
    For rw = 2 To wsConfig.Range("A1").CurrentRegion.Rows.Count
        If Range("E" & rw) <> 1 Then
            SQLQueryOut2 Range("A" & rw), Range("B" & rw), Range("C" & rw), Range("D" & rw)
            Range("F" & rw).Value = "Last Run: " & Format(Date, "DD/MM/YY") _
             & "_" & "" & Format(Now, "HH-MM-SS")
        Else
       'MsgBox Range("B" & rw) & " is omitted du to flag reported"
        End If
    Next rw
    MsgBox "Tables reported in Config have been updated"
    wsConfig.Select
End Sub

Open in new window


I would like to adapt this to postgresql to export tables related to a database in postgresql.

Could you advice how should I modify:

' ==> to modify
Set objConn = CreateObject("ADODB.Connection")
objConn.Open "Driver={SQL Server};" & _
"Server=" & strServer & ";" & _
"UID=user;" & _
"PWD=password;" & _
"Database=database;

Open in new window



Here is the information popup displayed in pgadmin.

User generated image
Thank you for your help.
SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Luis Diaz

ASKER

Thank you for your comment.

Now open that file with a text editor. Then you can copy the complete connection string.

Could you please provide an example. I don't know the syntax to be used for reference file.
D'oh? That's why I wrote that sentence before..

Create a empty text file, rename it's extension to .udl. Open that file and specify a working connection. Use the test button. Close it.

Now open that file with a text editor. Then you can copy the complete connection string.

Opening in the first sentence means the default: double-click.

btw, the primary resource for connection strings: https://connectionstrings.com
Thank you by working connection what do you mean?

The objective is to know how to transform this part:

' ==> to modify
Set objConn = CreateObject("ADODB.Connection")
objConn.Open "Driver={SQL Server};" & _
"Server=" & strServer & ";" & _
"UID=user;" & _
"PWD=password;" & _
"Database=database;

Open in new window


in postgresql.

I tested by using odbc drive through queries & connections tools available in excel and it works.

User generated image
but I don't know to adapat objConn
My attempt without success:

Set objConn = CreateObject("ADODB.Connection")
objConn.Open "Driver={PostgreSQL};" & _
"Server=" & strServer & ";" & _
"UID=test;" & _
"PWD=test;" & _
"Port=test;" & _
"Database=test;"

Open in new window


User generated image
Create a empty text file, rename it's extension to .udl. Open that file by double-clicking it..

User generated image
..and specify a working connection. Use the test button.

User generated image
Close it.

Now open that file with a text editor.

User generated image
Then you can copy the complete connection string.
Tested and I have the following message:
User generated image
I don't have the option to report port information in any tab.
I also changed the provider to ODBC and I got the following error.

User generated image
Well, did you use the wizard? Did you start on the first tab by selecting the Postgres provider?
Which driver should I select? I thought it was ODBC as I can access to the DB through it using excel connection feature.
You have choosen ADODB in your code, thus using ODBC is not necessary.

Which driver should I select?
The Postgres driver - which you have hopefullly already installed.
I have ODBC driver installed but I don't know which driver should I install for an ADOBD connection.
Thank you. Unable to do it right now. I will keep you informed.
Prior to installing the driver I want to make sure which should I install?
User generated image
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you and which version should I installed?
User generated image
Well, I would use the SE version.

But I haven't noticed that this is a commercial driver. So you may use the ODBC driver using the "OLEDB for ODBC driver" provider. But as already said, this comes normally with performance penalty.
What I don't understand is how can I report the port number when I select "OLEDB for ODBC driver".
User generated imageUser generated image
Ok, Now it works after installing the recommended driver.

User generated image

Now how should I proceed to set up the VBA procedure?

Thank you for your help.
I got the following information in .udl file:

Provider=PGNP.1;Password=XX;Persist Security Info=True;User ID=XX;Initial Catalog=XX;Data Source=XX;Extended Properties="PORT=XX;SSL=prefer;

Open in new window