Code to read the data from database and writing data in excel file using VB Macro and VBA.
'''' Naming the sub as auto_open will trigger the sub automatically on opening the file.
'''' We can create a sub with different name and assign macro to a control in the excel
''''file
Sub auto_open()
'''' define the connection string to connect to the database, it can be a dsn created,
'''' or connection string to create to the database. Please refer connectionstrings.com
'''' to connect to different database using connection string.
connStr = "dsn=testthedb''
'''' Query to fetch data from the database
strGetEmployeeDetails = "select * from employee order by UserName asc;"
''''Provide reference of sheet to add data to in the current workbook. We can add a
''''sheet in excel, or refer to an external excel file/Sheet using excel.application.
''''In this example, Sheet Employee_Details exist in the current excel file
Set worksht = ThisWorkbook.Sheets("Employee_Details")
''''--------------------------
'''' Create database connection
Set Conn = CreateObject("ADODB.Connection")
Set rset = CreateObject("ADODB.Recordset")
Conn.Open connStr
rset.Open strGetEmployeeDetails, Conn, adOpenStatic
''''The recordset is stored in rset.
''''The first row of data is the column details of the query results
''''and is added in the results header
For i = 0 To rset.Fields.Count - 1
worksht.Cells(2, i + 2) = rset.Fields(i).Name
Next i
''''Copy the recorset data into excel file starting at row 3 and column 2
worksht.Cells(3, 2).CopyFromRecordset rset
rset.Close
Set rset = Nothing
ThisWorkbook.Save
Conn.Close
Set Conn = Nothing
End Sub