\nThough Queries (SQL Statements) are categorized in many different categories like DDL<\/strong> (Data Definition Language), DML<\/strong> (Data Manipulation Language) etc. based their way of functioning. \nHere to execute a Query in excel macro, Queries can be categorized in to two categories:<\/p>\n1. Queries which returns NO records like DELETE, INSERT, UPDATE, ROLLBACK, COMMIT… etc.<\/h3>\n2. Queries which are tend to return records like SELECT queries. <\/h3>\n Method of executing both the queries, in excel macro, are different which are explained with example below.\n<\/p><\/blockquote>\n
1. Excel Macro to execute an INSERT, UPDATE, DELETE Statement in DB<\/h3>\n Queries which does not return any record after running, can be executed by “YourConnectionObject”<\/i>.Execute<\/strong> “Your Query”<\/i>. \nThis statement does not return anything. It simply executes your query and performs the respective operation.<\/p>\n Following is the Excel Macro Code which connects to the data base and execute your given query. It could be like INSERT Query, DELETE, UPDATE, COMMIT, ROLLBACK etc.<\/p>\n
\r\nFunction ExecuteQuery()\r\n\tDim DBcon As ADODB.Connection\r\n\tSet DBcon = New ADODB.Connection\r\n\tDim DBHost As String\r\n\tDim DBPort As String\r\n\tDim DBsid As String\r\n\tDim DBuid As String\r\n\tDim DBpwd As String\r\n\tDim DBQuery As String\r\n\tDim ConString As String\r\n\tOn Error GoTo err\r\n' DB connectivity details. Pass the correct connectivity details here\r\n\tDBHost = \"Host Address\"\r\n\tDBPort = \"Port Number\"\r\n\tDBsid = \"SID to Connect DB\"\r\n\tDBuid = \"User ID\"\r\n\tDBpwd = \"Password\"\r\n'Connection string to connect to Oracle using SID\r\n\tConString = \"Driver={Microsoft ODBC for Oracle}; \" & _\r\n\t\"CONNECTSTRING=(DESCRIPTION=\" & _\r\n\t\"(ADDRESS=(PROTOCOL=TCP)\" & _\r\n\t\"(HOST=\" & DBHost & \")(PORT=\" & DBPort & \"))\" & _\r\n\t\"(CONNECT_DATA=(SID=\" & DBsid & \"))); uid=\" & DBuid & \"; pwd=\" & DBpwd & \";\"\r\n'Open the connection using Connection String\r\n\tDBcon.Open (ConString) 'Connecion to DB is made\r\n\tDBQuery = \"Your Query\" 'like UPDATE, DELETE, INSERT etc.\r\n'below statement will execute the query\r\n\tDBcon.Execute DBQuery\r\n\tMsgBox (\"Query is successfully executed\")\r\n'Close the connection\r\n\tDBcon.Close\r\n\tExit Sub\r\n\terr:\r\n\tMsgBox \"Following Error Occurred: \" & vbNewLine & err.Description\r\n\tDBcon.Close\r\nEnd Function\r\n<\/code><\/pre>\n2. Excel Macro to execute a SELECT Statement which returns Records<\/h3>\n In this case when you run your query then you expect a set of recordset returned by the query and ofcourse!! you want to capture them and spread them in your workSheet. <\/p>\n
\nFollowing statement is used to execute a query to get get the recordset. RecordSetObject<\/i>.Open<\/strong> Your query<\/i>, DB Connection Object<\/i>. \nRefer the below excel macro which does following tasks:<\/p>\n 1. Makes connection with Oracle Database<\/p>\n
2. Executes your Query to get Record Set as a result of the Query<\/p>\n
3. Spread all the records in to your Excel Sheet named “Data”<\/i><\/strong><\/p>\nStatement used to spread all the records of a recordSet in Excel Sheet (Without Loop)<\/h3>\n Sheets(“data”).Range(“A2”)<\/i>.CopyFromRecordset<\/strong> RecordSetObject<\/i><\/p>\n <\/p>\n
\r\nFunction FetchRecordSetQuery()\r\n\t\r\n\tDim DBcon As ADODB.Connection\r\n\tDim DBrs As ADODB.Recordset\r\n\tSet DBcon = New ADODB.Connection\r\n\tSet DBrs = New ADODB.Recordset\r\n\tDim DBHost As String\r\n\tDim DBPort As String\r\n\tDim DBsid As String\r\n\tDim DBuid As String\r\n\tDim DBpwd As String\r\n\tDim DBQuery As String\r\n\tDim ConString As String\r\n Dim intColIndex as Integer\r\n\tOn Error GoTo err\r\n' DB connectivity details. Pass the correct connectivity details here\r\n\tDBHost = \"Host Address\"\r\n\tDBPort = \"Port Number\"\r\n\tDBsid = \"SID to Connect DB\"\r\n\tDBuid = \"User ID\"\r\n\tDBpwd = \"Password\"\r\n'Connection string to connect to Oracle using SID\r\n\tConString = \"Driver={Microsoft ODBC for Oracle}; \" & _\r\n\t\"CONNECTSTRING=(DESCRIPTION=\" & _\r\n\t\"(ADDRESS=(PROTOCOL=TCP)\" & _\r\n\t\"(HOST=\" & DBHost & \")(PORT=\" & DBPort & \"))\" & _\r\n\t\"(CONNECT_DATA=(SID=\" & DBsid & \"))); uid=\" & DBuid & \"; pwd=\" & DBpwd & \";\"\r\n'Open the connection using Connection String\r\n\tDBcon.Open (ConString) 'Connecion to DB is made\r\n\tDBQuery = \"Your Query\" 'like UPDATE, DELETE, INSERT etc.\r\n'below statement will execute the query and stores the Records in DBrs\r\n\tDBrs.Open DBQuery, DBcon\r\n\tIf Not DBrs.EOF Then 'to check if any record then\r\n' Spread all the records with all the columns\r\n' in your sheet from Cell A2 onward.\r\n\t\tSheets(\"data\").Range(\"A2\").CopyFromRecordset DBrs\r\n'Above statement puts the data only but no column\r\n'name. hence the below for loop will put all the\r\n'column names in your excel sheet.\r\n\t\tFor intColIndex = 0 To DBrs.Fields.Count - 1 ' recordset fields\r\n\t\t\tSheets(\"data\").Cells(1, intColIndex + 1).Value = DBrs.Fields(intColIndex).Name\r\n\t\tNext\r\n\tEnd If\r\n'Close the connection\r\n\tDBcon.Close\r\n\tExit Function\r\n\terr:\r\n\tMsgBox \"Following Error Occurred: \" & vbNewLine & err.Description\r\n\tDBcon.Close\r\nEnd Function\r\n<\/code><\/pre>\n\n\nAbove codes are examples to show, how to execute a query and spread the records across the Excel Sheet without using a Loop. I have taken an example of connecting Oracle Database using SID connection. If you have to connect to some other database using Service etc then go through my previous articles to get the Connection String for such connections. If you still face any issue regarding connecting to your DB or querying the DB kindly mail me.<\/h3>\n<\/blockquote>\n<\/span>","protected":false},"excerpt":{"rendered":"In continuation to one of my article which shares the connection strings to connect to different data bases. In this article I explained and shared every possible VBA code to make connection with many databases like Oracle, SQL etc. but does the Story ends there?? NO WAY !! That’s the starting point. You are going […]<\/p>\n","protected":false},"author":45,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[5203,1246,1675],"tags":[],"class_list":["post-4139","post","type-post","status-publish","format-standard","hentry","category-database","category-macro","category-excel-macro-for-beginners"],"yoast_head":"\n
VBA to Query Database and Spread the Records in Excel - Let's excel in Excel<\/title>\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\t \n\t \n\t \n \n \n \n \n \n\t \n\t \n\t \n