Using a workbook connection in VBA

Murphy1

New Member
Joined
Apr 30, 2016
Messages
2
Hi , I'm would like to use an existing workbook connection (based on an ODC file) and then change the command text from a SQL statement constructed in the spreadsheet. Getting the SQL is no problem but how do I call an existing workbook connection and then execute this with the new SQL statement.

I have created a connection via the UI and called it MyConnection.

This is what I have been testing but it fails.

Public Function GetDataSet()

'' Test config
Dim ConnName As String
Dim WorksheetName As String
Dim StartCellValue As String
Dim SQLString As String
Dim TableName As String


StartCellValue = "$A$1"
WorksheetName = "Sheet1"
SQLString = "SELECT MyField From MyTable"
TableName = "Test1"
ConnName = "MyConnection"

'Set the active worksheet
Worksheets(WorksheetName).Activate

With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=ActiveWorkbook.Connections(ConnName), Destination:=Range(StartCellValue)).TableObject
.ListObject.DisplayName = TableName
.Refresh
End With

End Function
 

Excel Facts

Add Bullets to Range
Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)
The question is really about the correct method to use the connection , change the commandtext and then execute the code. Thanks
 
Upvote 0

Forum statistics

Threads
1,216,026
Messages
6,128,363
Members
449,444
Latest member
abitrandom82

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top