I would like to import a dataset from a MySQL database into Excel not using additional references or add-ins (so colleagues can use it without changing anything in their setup). The solutions I have found so far all use additional references or things that are not active by default.
The database contains a growing number of datasets all named in a standardised way and the user should be able to choose which dataset to import. I am a VBA-semi-noob and have managed to get the basic idea working for one specific dataset (using macro editor) , but I am unable to get it working with variable dataset names.
What works so far is the following (dataset name in this example is "scada_pl_oxidation_study_14102020", database is currently local but will change to remote in future)
'Insert table from MySQL database
Application.CutCopyMode = False
Sheets("Raw Data").Select
Range("A1").Select
ActiveWorkbook.Queries.Add Name:= _
"cndatabase scada_pl_oxidation_study_14102020", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = MySQL.Database(""localhost"", ""cndatabase"", [ReturnSingleDatabase=true])," & Chr(13) & "" & Chr(10) & " cndatabase_scada_pl_oxidation_study_14102020 = Source{[Schema=""cndatabase"",Item=""scada_pl_oxidation_study_14102020""]}[Data]" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " cndatabase_scada_pl_oxidation_study_14102020"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array( _
"OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""cndatabase scada_pl_oxidation_study_14102020"";Extended Pr" _
, "operties="""""), Destination:=Range("'Raw Data'!$A$3")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array( _
"SELECT * FROM [cndatabase scada_pl_oxidation_study_14102020]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "cndatabase_scada_pl_oxidation_study_14102020"
.Refresh BackgroundQuery:=False
End With
My initial idea was to use a Userform to just type the name of the dataset to be imported, but replacing the "scada_pl_oxidation_study_14102020" with a variable based on the Userform input does not seem to work. A solution where the user can choose from a list of datasets contained in the database would be preferred, but that is way beyond my capabilities. Can anybody help me with this?