A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
Hi TodLay
Once you have a query on a worksheet, you can programmatically have that query return any result set. Like anything else, it's easy (or not so easy) once you have an example that works.
If I understand your request, you want to be able to specify a query and then execute that query programmatically in Excel 2016 for Mac.
As things stand, you can almost do this. There is a broken VBA command that is a blocking issue.
Here's a code example that works in Windows connecting to SQL Server. It should work generically for any ODBC connection assuming you change the Driver parameters appropriately.
'Query the database
Sheets("FullRecordFromSS").Select
ActiveSheet.Unprotect
DoEvents
Range("Table_ExternalData_1[ID]").Select
Let stSQL1 = "SELECT * FROM libInfo.dbo.tblMain where LibUserID = " & "'" & SelectedLibUserID & "'" & ";"
Range("A2").Select
With ActiveWorkbook.Connections("GetRecordToUpdate").ODBCConnection
.BackgroundQuery = True
.CommandText = stSQL1
.CommandType = xlCmdSql
.Connection = _
"ODBC;DRIVER=SQL Server;SERVER=servername,14360;UID=UserId;PWD=Password;APP=Microsoft Office 2016;WSID=credential"
.RefreshOnFileOpen = False
.SavePassword = True
.SourceConnectionFile = ""
.SourceDataFile = ""
.ServerCredentialsMethod = xlCredentialsMethodIntegrated
.AlwaysUseConnectionFile = False
End With
'
'Run the query
ActiveSheet.Unprotect
Range("A2").Select
Selection.ListObject.QueryTable.Refresh BackgroundQuery:=True
End If
If you try to run this code on a Mac, it halts at the line:
With ActiveWorkbook.Connections("GetRecordToUpdate").ODBCConnection
The code does successfully change the query in the querytable, but you can't refresh the query programmatically. This example does show the syntax for building your query. Notice how you have to use quotation marks to parse the query.
If you want to encourage Microsoft fix the broken VBA statement, please click here to vote for and discuss this topic:
https://excel.uservoice.com/forums/304933-excel-for-mac/suggestions/18814606-vba-odbc-connection