- Excel VBA - Basics (24)
- VBA User Forms (21)
- Excel VBA - pivot tables (9)
- Excel VBA - charts (6)
- VBA - advanced (13)
- VBA - working with files (11)
- VBA - linking applications (10)
- VBA - working with Outlook (14)
- Built-in VBA functions (9)
- VBA - working with data (55)
- VBA - scraping websites (24)
- VBA - working with shapes (3)
- VBA - classes and structures (6)
VBA - WORKING WITH DATA VIDEOS▼
- Excel VBA Part 30 - Querying a Database with ADO
- Excel VBA Part 31 - Modifying Data with ADO Recordsets
- Excel VBA Part 32 - Executing SQL Commands with ADO
- Excel VBA Part 56.1 - Connect to SQL Server using ADO
- Excel VBA Part 56.2 - Get Data from SQL Server with ADO Recordsets
- Excel VBA Part 56.3 - Read and Execute SQL Query Files
- Excel VBA Part 56.4 - Return Multiple Result Sets from SQL Queries
- Excel VBA Part 56.5 - Basic ADO Commands with SQL Server
- Excel VBA Part 56.6 - ADO Commands and Parameters
- Excel VBA Part 56.7 - ADO Commands and Stored Procedures
- Excel VBA Part 58.1 - SQL for Excel Files - Basic Select Statements
- Excel VBA Part 58.2 - SQL for Excel Files - Sorting Rows in a Query
- Excel VBA Part 58.3 - SQL for Excel Files - Selecting the Top N Rows
- Excel VBA Part 58.4 - SQL for Excel Files - Selecting All or Distinct Rows
- Excel VBA Part 58.5 - SQL for Excel Files - Basic Criteria in Queries
- Excel VBA Part 58.6 - SQL for Excel Files - Text Criteria and the Like Operator
- Excel VBA Part 58.7 - SQL for Excel Files - Basic Calculated Columns
- Excel VBA Part 58.8 - SQL for Excel Files - Conditional Functions
- Excel VBA Part 58.9 - SQL for Excel Files - Nulls in Expressions
- Excel VBA Part 58.10 - SQL for Excel Files - Date Expressions
- Excel VBA Part 58.11 - SQL for Excel Files - Text Expressions
- Excel VBA Part 58.12 - SQL for Excel Files - Aggregation Functions
- Excel VBA Part 58.13 - SQL for Excel Files - Grouping Rows
- Excel VBA Part 58.14 - SQL for Excel Files - Criteria in the Having Clause
- Excel VBA Part 58.15 - SQL for Excel Files - Pivoting Data (Crosstab Queries)
- Excel VBA Part 58.16 - SQL for Excel Files - Basic Union Queries
- Excel VBA Part 58.17 - SQL for Excel Files - Union Queries with Total Rows
- Excel VBA Part 58.18 - SQL for Excel Files - Union Queries from Multiple Files
- Excel VBA Part 58.19 - SQL for Excel Files - Inner Joins
- Excel VBA Part 58.20 - SQL for Excel Files - Outer Joins
- Excel VBA Part 58.21 - SQL for Excel Files - Constructing Full Outer Joins
- Excel VBA Part 58.22 - SQL for Excel Files - Join Worksheets from Multiple Files
- Excel VBA Part 58.23 - SQL for Excel Files - Merge Worksheets Side by Side
- Excel VBA Part 58.24 - SQL for Excel Files - Consolidate Worksheets using Derived Tables
- Excel VBA Part 58.25 - SQL for Excel Files - Basic Subqueries
- Excel VBA Part 58.26 - SQL for Excel Files - Nested Subqueries
- Excel VBA Part 58.27 - SQL for Excel Files - Correlated Subqueries
- Excel VBA Part 58.28 - SQL for Excel Files - Inserting Data into an Existing Sheet
- Excel VBA Part 58.29 - SQL for Excel Files - Selecting Data into a New Sheet or Workbook
- Excel VBA Part 58.30 - SQL for Excel Files - Updating Existing Data
- Excel VBA Part 58.31 - SQL for Excel Files - Split a Table into Separate Sheets
- How do I pass Japanese text to a stored procedure parameter in VBA?
- How do I get data from a closed Excel file using VBA?
- How do I loop through worksheets in a closed workbook with VBA?
- How do I get data from multiple closed Excel files using VBA?
- How do I get data from multiple workbooks with one query in VBA?
- How do I loop through worksheets in multiple closed workbooks in VBA?
- How do I populate a listbox using an ADO recordset in VBA?
- How do I get the column names from an ADO recordset?
- Excel VBA - How do I get data from a CSV file using ActiveX Data Objects
- How do I add a filename to the results of an ADODB recordset?
- How do I populate an array with an ADODB recordset?
- How do I count the rows in an ADODB recordset?
- How do I find the data type of a column in an ADODB recordset?
- How do I refer to a field name with a dot in an ADO SQL query?
VBA - working with data videos | Excel VBA Part 56.2 - Get Data from SQL Server with ADO Recordsets
Posted by Andrew Gould on 24 June 2019
This video shows you how to extract data from a SQL Server database using the ActiveX Data Objects (ADO) library for VBA and the Microsoft OLE DB Driver for SQL Server. You'll learn how to write a connection string to connect to a SQL Server databse and how to use a recordset to retrieve data. You'll learn how to populate the recordset using SQL Server tables, views, stored procedures and select statements and how to write the data you've retrieved into an Excel Worksheet.
This video has the following accompanying files:
|01 Create Movies Database 2016.sql||SQL query|
|02 Create Oscar Winners View.sql||SQL query|
|03 Create Oscar Winners Procedure.sql||SQL query|
|Get Data from SQL Server with ADO Recordsets.xlsm||Excel workbook with macros|
Click to download a zipped copy of the above files.
There are no exercises for this video.
Making a video bigger
You can increase the size of your video to make it fill the screen like this:
Play your video (the icons shown won't appear until you do), then click on the full screen icon which appears as shown at its bottom right-hand corner.
When you've finished viewing a video in full screen mode, just press the Esc key to return to normal view.
Improving the quality of a video
To improve the quality of a video, first click on the Settings icon:
Make sure you're playing your video so that the icons shown appear, then click on this gear icon at the bottom right-hand corner.
Choose to change the video quality:
Click on Quality as shown to bring up the submenu.
The higher the number you choose, the better will be your video quality (but the slower the connection speed):
Don't choose the HD option unless you have a fast enough connection speed to support it!
Is your Wise Owl speaking too slowly (or too quickly)? You can also use the Settings menu above to change your playback speed.
Awesome video and thank you.
I think there are some bugs with the CopyFromRecordset property when using MySQL drivers.
To be more specific, when I use this property then some of the fetched data come in a truncated version, say instead of Consumer Staples it is fetched as Consumer.
Having searched the web I found a property of the Recordset object as per below:
rs.CursorLocation = adUseClient
Indeed this addition provides me with a solution, but I quite do not get the reason why even when I read info in the link below. May I kindly ask you to elaborate on what this property does and its current value "adUseClient"?
Hi! There's a pretty good description of some of the implications of using server-side or client-side cursors here https://stackoverflow.com/questions/56037800/difference-between-ado-client-side-vs-server-side-cursor-when-the-sql-server-dat
I don't know MySQL well enough to explain why you see the results you do but I hope the link above gives you a little more information.
Hello Andrew, for some reason my code didn't work so I had to record it step by step. Here how it looks
Dim i As Long
Application.CutCopyMode = False
.BackgroundQuery = False
.CommandType = xlCmdSql
.connection = _
"OLEDB;Provider=SQLOLEDB.1;Password=XXX;Persist Security Info=True;User ID=XXX;Data Source=MYSERVER;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
.CommandText = Array( _
"SELECT * FROM REPORT.dbo.PROJECTS as w WHERE w.""Project Number"" " & _
"like '" & Lists.Range("C4").Value & "%' or w.""Project Number"" like '" & Lists.Range("C3").Value & "%' or w.""Project Number"" not like '" & Lists.Range("C9").Value & "%'" _
.RefreshOnFileOpen = False
.SavePassword = True
.SourceConnectionFile = ""
.SourceDataFile = ""
.ServerCredentialsMethod = xlCredentialsMethodIntegrated
.AlwaysUseConnectionFile = False
.Name = "DATABASE"
.Description = ""
Application.CutCopyMode = False
With Test.ListObjects.Add(SourceType:=4, Source:=ActiveWorkbook. _
.RowNumbers = False
.PreserveFormatting = True
.RefreshStyle = 1
.AdjustColumnWidth = True
.ListObject.DisplayName = "Table_DATABASE_Query"
My questions would be:
1. Not sure what the difference is between OLEDB and ADODB, does it matter?
2. I have a VERY long SQL statement, so I tried to break it in lines and it didn't work (I have more than 25 lines). Is there a way for me to break it by variables? I tried it by looking at these websites, but it doesn't work for me
Thank you so much.
In VBA, ADODB is an object library which allows you to write code to connect to a database using several types of connection, of which OLEDB is one. The code shown in the video uses the ADODB library to create a Connection object which establishes an OLEDB connection to a SQL Server database. The technique you've used along with the macro recorder is quite different (I'm guessing you used Data > Get Data > From SQL Server Database from the Excel ribbon) and doesn't use the ADODB library at all. It's up to you which technique you prefer!
The solutions shown in the links you provided are good so I'm not sure why your code still isn't working. If your query is still too long you could try the technique shown in this video https://www.wiseowl.co.uk/vba-macros/videos/vba-ado-net-recordsets/ado-execute-sql-query-file/ which stores the query in a separate text file and has VBA read it.
I hope that helps!
Hello Andrew, I have an issue with my code, I'm trying to follow your code suggestion I appreciate if you can please help me. I'm getting Run-Time error '-2147217900 (80040e14)'
[Microsoft] [ODBC SQL Server Driver] [SQL Server] An expression of non-boolean type specified in a context where a condition is expected near "number".
Ideally, my SQL contains SELECT within SELECT statement, i.e. several databases joined with "LEFT Outer join" with input parameters "WHERE project number is like 'P-10500%' or 'P-10600%'
But I tried to construct a code so that at least it can read the database. In Connection string should I put Schema name or I need to list database names if it is more than one database? How can I construct a VBA code for it?
Here's my start code:
Dim ws As Worksheet
Dim f As ADODB.Field
Dim i As Integer
Dim myservername As String
Dim mydatabase As String
Dim myuserid As String
Dim mypasswd As String
Dim cn As ADODB.connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.connection
cn.ConnectionString = " Provider=MSDASQL.1;Persist Security Info=True;DRIVER=SQL Server; DATABASE: REPORT;SERVER=MYSERVER;UID=ALBERTAN;PWD=PW;APP=Microsoft Office 2016;WSID=XXX"
Set rs = New ADODB.Recordset
rs.ActiveConnection = cn
rs.Source = "SELECT * FROM (SELECT * FROM REPORT 2 as a Left Outer Join Report 3 as b on a.costcode = b.costcode w WHERE w.Job Number like 'p-10500%' OR ‘P-10600%’”
rs.CursorType = adOpenForwardOnly
rs.LockType = adLockReadOnly
Set ws = Worksheets.Add
For Each f In ResultSet.Fields
i = i + 1
ws.Cells(1, i).Value = f.Name
Range("A1").CurrentRegion.WrapText = False
Hi Albert, I believe the problem is in the WHERE clause. Yours looks like this:
WHERE project number is like 'P-10500%' or 'P-10600%'
But it should look like this
WHERE [project number] like 'P-10500%' or [project number] like 'P-10600%'
When a column name contains a space it needs to be enclosed in square brackets.
When using a logical operator like AND or OR, you need to include a full logical test on each side of the operator.
I hope that helps!