There are many ways to get data from external sources into a worksheet
You can also get data from the Internet, text files or other Excel or
So we need a database connection (variable varConn in the macro below) and SQL query (variable varSQL ) to automate the retrieval of data from the database for the report. In the example below there is SQL query , which receives data from a small database in MS Access.
Click load the database
The MS Access file will look like this:
Let's write our macro that will execute SQL query .
Open the menu Service - Macro - Editor Visual Basic , insert the new module (menu Insert - Module ) and copy the macro text there:
Sub SQLQuery_1() 'moonexcel.com.ua Dim varConn As String Dim varSQL As String Range("A1").CurrentRegion.ClearContents varConn = "ODBC;Driver={Microsoft Access Driver (*.mdb, *.accdb)}" varSQL = "SELECT Month, Product, City FROM Sumproduct" With ActiveSheet.QueryTables.Add(Connection:=varConn, Destination:=Range("A1")) .CommandText = varSQL .Refresh BackgroundQuery:=False End With End Sub
Click save and return to Excel. Choose from the menu View - Macros (Alt+F8) the name of our macro " SQLQuery_1 ". A dialog box will appear, press it Database... , look for our Access file and click
Now we can see that our macro query has pulled up the columns
Similarly, we can get data from a regular Excel file as if from a database. For this, the code of our macro needs to be slightly rewritten and the connection driver changed from Access to Excel.
We export the table
Sub SQLQuery_2() 'moonexcel.com.ua Dim varConn As String Dim varSQL As String Range("A1").CurrentRegion.ClearContents varConn = "ODBC;Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)}" varSQL = "SELECT Month, Product, City FROM Sumproduct" With ActiveSheet.QueryTables.Add(Connection:=varConn, Destination:=Range("A1")) .CommandText = varSQL .Refresh BackgroundQuery:=False End With End Sub
A window will appear where we can select our Excel file (should be called