<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>youdidwhatwithtsql.com &#187; VBA</title>
	<atom:link href="http://www.youdidwhatwithtsql.com/tag/vba/feed" rel="self" type="application/rss+xml" />
	<link>http://www.youdidwhatwithtsql.com</link>
	<description>making DBAs everywhere curse!</description>
	<lastBuildDate>Wed, 01 Sep 2010 17:02:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Practical VBA Examples for the DBA: Part 2</title>
		<link>http://www.youdidwhatwithtsql.com/practical-vba-examples-for-the-dba-part-2/308</link>
		<comments>http://www.youdidwhatwithtsql.com/practical-vba-examples-for-the-dba-part-2/308#comments</comments>
		<pubDate>Wed, 05 Aug 2009 19:53:12 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[VBA]]></category>
		<category><![CDATA[DBA]]></category>
		<category><![CDATA[Excel]]></category>
		<category><![CDATA[Visual Basic for Applications]]></category>

		<guid isPermaLink="false">http://www.youdidwhatwithtsql.com/practical-vba-examples-for-the-dba-part-2/308</guid>
		<description><![CDATA[In a previous post I demonstrated how a little bit of VBA code can be used&#160; to build some basic user interfaces to deliver data. Continuing on with this the examples here will show how to build some basic user interfaces; Combo box (or drop down list) and a Multi-Select List. Like the previous examples [...]<p>Post from: <a href="http://www.youdidwhatwithtsql.com">youdidwhatwithtsql.com</a><br/><br/><a href="http://www.youdidwhatwithtsql.com/practical-vba-examples-for-the-dba-part-2/308">Practical VBA Examples for the DBA: Part 2</a></p>
]]></description>
			<content:encoded><![CDATA[<p>In a <a href="http://www.youdidwhatwithtsql.com/practical-vba-examples-dba-part-1/268" target="_blank">previous post</a> I demonstrated how a little bit of <a href="http://en.wikipedia.org/wiki/Visual_Basic_for_Applications" target="_blank">VBA</a> code can be used&#160; to build some basic user interfaces to deliver data. Continuing on with this the examples here will show how to build some basic user interfaces; Combo box (or drop down list) and a Multi-Select List. Like the previous examples these use the <a href="http://msdn.microsoft.com/en-us/library/ms124501.aspx" target="_blank">AdventureWorks</a> sample database as a data source.</p>
<p><strong>Using VBA Combo Boxes with SQL Server</strong></p>
<p>This example will present the user with a drop down list so the user can make a selection and return the appropriate data. To get started first open up Excel.</p>
<p>Click the “Visual Basic” button on the Developer ribbon. N.B. If you can’t see it <a href="http://blogs.msdn.com/erikaehrli/archive/2006/06/06/ribbondevelopertab.aspx" target="_blank">enable the Developer ribbon</a>.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/excel_2007_developer_ribbon.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="The Developer Ribbon in Excel 2007" border="0" alt="The Developer Ribbon in Excel 2007" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/excel_2007_developer_ribbon_thumb.png" width="644" height="142" /></a> </p>
<p>Firstly we need to add a reference to allow Excel to interact with <a href="http://www.microsoft.com/sqlserver/2008/en/us/default.aspx" target="_blank">SQL Server</a>. In the Visual Basic editor click Tools &gt; References and tick the box next to “Microsoft ActiveX Data Objects 2.8 Library”. You’ll get runtime errors if this step isn’t done.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/activex_data_objects_reference.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Adding a reference to ADO in Excel." border="0" alt="Adding a reference to ADO in Excel." src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/activex_data_objects_reference_thumb.png" width="244" height="197" /></a> </p>
<p>In the project tree right click UserForm &gt; Insert &gt; UserForm. This form should be called UserForm1 (ensure it does as we will be referencing this name in VBA code.)</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/UserForm1_3.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Building simple GUIs with VBA" border="0" alt="Building simple GUIs with VBA" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/UserForm1_3_thumb.png" width="244" height="157" /></a> </p>
<p>In the properties dialog for UserForm1 change the value for Caption to “Select a Product”. From the toolbox palette drag and drop and <a href="http://www.excel-vba.com/vba-forms-3-7-combo-boxes.htm" target="_blank">ComboBox</a> and a <a href="http://www.excel-vba.com/vba-forms-3-4-command-buttons.htm" target="_blank">CommandButton</a> onto the UserForm1. These components should be called <strong>ComboBox1</strong> and <strong>CommandButton1</strong>. You should end up with something that looks like this.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/ComboBox1_4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Simple form with VBA." border="0" alt="Simple form with VBA." src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/ComboBox1_4_thumb.png" width="244" height="108" /></a> </p>
<p>Save your work and close the VBA editor. In the Developer ribbon click the Macros button and add a new macro called <strong>comboBox</strong>. Add the following code to the macro. Make sure you change the <a href="http://www.connectionstrings.com/" target="_blank">connection string</a> for your environment.</p>
<pre lang="Visual BASIC">Sub comboBox()

    ' Setup connection string
    Dim connStr As String
    connStr = &quot;driver={sql server};server=localhost\sql2005;&quot;
    connStr = connStr &amp; &quot;Database=AdventureWorks;TrustedConnection=True;&quot;

    ' Setup the connection to the database
    Dim connection As ADODB.connection
    Set connection = New ADODB.connection
    connection.connectionString = connStr
    ' Open the connection
    connection.Open

    ' Open recordset.
    Set Cmd1 = New ADODB.Command
    Cmd1.ActiveConnection = connection
    Cmd1.CommandText = &quot;SELECT Name FROM Production.Product ORDER BY Name&quot;
    Set Results = Cmd1.Execute()

    Results.MoveFirst
    While Not Results.EOF

        ' Fill the Combo box with product names
        UserForm1.ComboBox1.AddItem Results.Fields(&quot;Name&quot;).Value
        Results.MoveNext

    Wend

    UserForm1.Show

End Sub</pre>
<p>This code will select product names from Production.Product and fill the combo box before displaying the form. Go back to UserForm1 and double click the <a href="http://www.excel-vba.com/vba-forms-3-4-command-buttons.htm" target="_blank">CommandButton</a>. This will open up the VBA code editor. Here we can associated an action with the button. Paste the below code into the editor replacing any code already in there. Change the <a href="http://www.connectionstrings.com" target="_blank">connection string</a> to point at your <a href="http://www.microsoft.com/sqlserver/2008/en/us/default.aspx" target="_blank">SQL Server</a>.</p>
<pre lang="Visual BASIC">Private Sub CommandButton1_Click()

    Dim selection As String
    ' Get the selected product escaping single quotes
    selection = Replace(UserForm1.ComboBox1.Value, &quot;'&quot;, &quot;''&quot;)

    ' Setup connection string
    Dim connStr As String
    connStr = &quot;driver={sql server};server=localhost\sql2005;&quot;
    connStr = connStr &amp; &quot;Database=AdventureWorks;TrustedConnection=True;&quot;

    ' Setup the connection to the database
    Dim connection As ADODB.connection
    Set connection = New ADODB.connection
    connection.connectionString = connStr
    ' Open the connection
    connection.Open

    ' Open recordset.
    Set Cmd1 = New ADODB.Command
    Cmd1.ActiveConnection = connection
    Cmd1.CommandText = &quot;SELECT * FROM Purchasing.PurchaseOrderDetail t1 INNER JOIN Production.Product t2 ON t1.ProductID = t2.ProductID AND t2.Name ='&quot; &amp; selection &amp; &quot;'&quot;
    Set Results = Cmd1.Execute()

    ' Clear the data from the active worksheet
    Cells.Select
    Cells.ClearContents

    ' Add column headers to the sheet
    headers = Results.Fields.Count
    For iCol = 1 To headers
        Cells(1, iCol).Value = Results.Fields(iCol - 1).Name
    Next

    ' Copy the resultset to the active worksheet
    Cells(2, 1).CopyFromRecordset Results

    ' Stop running the macro
    Unload Me

End Sub</pre>
<p>Save the code and return to Excel. The macro should be ready to run. Click the Macros button on the Developer ribbon. Choose <strong>ComboBox</strong> and click Run. If all is ok you will see the combobox populated with product names.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/select_a_product_5.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="ComboBox with VBA" border="0" alt="ComboBox with VBA" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/select_a_product_5_thumb.png" width="244" height="124" /></a> </p>
<p>Pick “Adjustable Race” and click “Choose Product”. Data should be returned in the open workbook.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/returned_data_6.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Order information for the selected product." border="0" alt="Order information for the selected product." src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/returned_data_6_thumb.png" width="244" height="149" /></a> </p>
<p><strong>Using VBA Multi-Select Lists (ListBox) with SQL Server</strong></p>
<p><font color="#666666">This example is very similar to the previous</font> one but this time we will allow the user to select more than one product by using a Multi-Select list or <a href="http://msdn.microsoft.com/en-us/library/aa223123(office.11).aspx" target="_blank">ListBox</a>.</p>
<p>Follow the same process above to create a new form. This form should be called <strong>UserForm2</strong>. Add a <a href="http://msdn.microsoft.com/en-us/library/aa223123(office.11).aspx" target="_blank">ListBox</a> and call it <strong>listProducts</strong> then add a button and call it <strong>btnProducts</strong>. You should end up with something looking like below;</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/UserForm2_7.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="ListBox in VBA" border="0" alt="ListBox in VBA" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/UserForm2_7_thumb.png" width="244" height="149" /></a> </p>
<p>Save and return to Excel and add a new macro called <strong>selectList</strong> . Add the following code to the macro. Change the <a href="http://www.connectionstrings.com" target="_blank">connection string</a> as appropriate.</p>
<pre lang="Visual BASIC">Sub selectList()

    ' Setup connection string
    Dim connStr As String
    connStr = &quot;driver={sql server};server=localhost\sql2005;&quot;
    connStr = connStr &amp; &quot;Database=AdventureWorks;TrustedConnection=True;&quot;

    ' Setup the connection to the database
    Dim connection As ADODB.connection
    Set connection = New ADODB.connection
    connection.connectionString = connStr
    ' Open the connection
    connection.Open

    ' Open recordset.
    Set Cmd1 = New ADODB.Command
    Cmd1.ActiveConnection = connection
    Cmd1.CommandText = &quot;SELECT Name FROM Production.Product ORDER BY Name&quot;
    Set Results = Cmd1.Execute()

    UserForm2.listProducts.MultiSelect = fmMultiSelectMulti
    Results.MoveFirst
    While Not Results.EOF

        UserForm2.listProducts.AddItem Results.Fields(&quot;Name&quot;).Value
        Results.MoveNext

    Wend

    UserForm2.Show
End Sub</pre>
<p>This code will populate the <a href="http://www.excel-vba.com/vba-forms-3-8-list-boxes.htm" target="_blank">ListBox</a> with product names and display the form when the macro is executed. Return to the VBA editor and double click on <strong>btnProducts</strong>. Add the below code and not forgetting to change the <a href="http://www.connectionstrings.com" target="_blank">connection string</a>.</p>
<pre lang="Visual BASIC">Private Sub btnProducts_Click()

    Dim selection As String
    ' Get the selected products escaping single quotes
    'selection = Replace(UserForm2.listProducts.Value, &quot;'&quot;, &quot;''&quot;)
    Dim lItem As Long

    For lItem = 0 To listProducts.ListCount - 1

        If listProducts.Selected(lItem) = True Then

            selection = selection &amp; &quot;'&quot; &amp; Replace(listProducts.List(lItem), &quot;'&quot;, &quot;''&quot;) &amp; &quot;',&quot;
        End If
    Next

    selection = Mid(selection, 1, Len(selection) - 1)

    ' Setup connection string
    Dim connStr As String
    connStr = &quot;driver={sql server};server=localhost\sql2005;&quot;
    connStr = connStr &amp; &quot;Database=AdventureWorks;TrustedConnection=True;&quot;

    ' Setup the connection to the database
    Dim connection As ADODB.connection
    Set connection = New ADODB.connection
    connection.connectionString = connStr
    ' Open the connection
    connection.Open

    ' Open recordset.
    Set Cmd1 = New ADODB.Command
    Cmd1.ActiveConnection = connection
    Cmd1.CommandText = &quot;SELECT * FROM Purchasing.PurchaseOrderDetail t1 INNER JOIN Production.Product t2 ON t1.ProductID = t2.ProductID AND t2.Name IN (&quot; &amp; selection &amp; &quot;)&quot;
    Set Results = Cmd1.Execute()

    ' Clear the data from the active worksheet
    Cells.Select
    Cells.ClearContents

    ' Add column headers to the sheet
    headers = Results.Fields.Count
    For iCol = 1 To headers
       Cells(1, iCol).Value = Results.Fields(iCol - 1).Name
    Next

    ' Copy the resultset to the active worksheet
    Cells(2, 1).CopyFromRecordset Results

    ' Stop running the macro
    Unload Me

End Sub</pre>
<p>Save and return to Excel. The macro should be ready to run. Click the Macros button on the Developer ribbon and run the macro called “selectList”.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/select_list_8.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="VBA ListBox" border="0" alt="VBA ListBox" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/select_list_8_thumb.png" width="244" height="186" /></a> </p>
<p>Select some products and “Sheet1” should be populated with the appropriate data.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/Excel_data_9.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Order information for multiple products." border="0" alt="Order information for multiple products." src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/09/Excel_data_9_thumb.png" width="244" height="151" /></a> </p>
</p>
<p>Hopefully this has been easy to follow. I don’t profess to be a <a href="http://en.wikipedia.org/wiki/Visual_Basic_for_Applications" target="_blank">VBA</a> expert, or enthusiast,&#160; but I do see its use for quickly building interfaces around your data.</p>
<p><map name='google_ad_map_308_a45beff5d2e172f6'>
<area shape='rect' href='http://imageads.googleadservices.com/pagead/imgclick/308?pos=0' coords='1,2,367,28' />
<area shape='rect' href='http://services.google.com/feedback/abg' coords='384,10,453,23'/></map>
<img usemap='#google_ad_map_308_a45beff5d2e172f6' border='0' src='http://imageads.googleadservices.com/pagead/ads?format=468x30_aff_img&amp;client=&amp;channel=&amp;output=png&amp;cuid=308&amp;url=http%3A%2F%2Fwww.youdidwhatwithtsql.com%2Fpractical-vba-examples-for-the-dba-part-2%2F308' title="Practical VBA Examples for the DBA: Part 2" alt=" Practical VBA Examples for the DBA: Part 2" /></p><p>Post from: <a href="http://www.youdidwhatwithtsql.com">youdidwhatwithtsql.com</a><br/><br/><a href="http://www.youdidwhatwithtsql.com/practical-vba-examples-for-the-dba-part-2/308">Practical VBA Examples for the DBA: Part 2</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.youdidwhatwithtsql.com/practical-vba-examples-for-the-dba-part-2/308/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Practical VBA Examples for the DBA: Part 1</title>
		<link>http://www.youdidwhatwithtsql.com/practical-vba-examples-dba-part-1/268</link>
		<comments>http://www.youdidwhatwithtsql.com/practical-vba-examples-dba-part-1/268#comments</comments>
		<pubDate>Mon, 20 Jul 2009 09:00:00 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[VBA]]></category>
		<category><![CDATA[Visual Basic for Applications]]></category>

		<guid isPermaLink="false">http://www.youdidwhatwithtsql.com/?p=268</guid>
		<description><![CDATA[I’ve never been a huge fan of VBA but it can be very useful for quickly providing interfaces to your databases. The examples here use Macros in Excel 2007 to execute stored procedures on SQL Server and provide data back to the user. These examples use the AdventureWorks sample database. Execute a Stored Procedure with [...]<p>Post from: <a href="http://www.youdidwhatwithtsql.com">youdidwhatwithtsql.com</a><br/><br/><a href="http://www.youdidwhatwithtsql.com/practical-vba-examples-dba-part-1/268">Practical VBA Examples for the DBA: Part 1</a></p>
]]></description>
			<content:encoded><![CDATA[<p>I’ve never been a huge fan of <a href="http://en.wikipedia.org/wiki/Visual_Basic_for_Applications" target="_blank">VBA</a> but it can be very useful for quickly providing interfaces to your databases. The examples here use <a href="http://office.microsoft.com/en-us/excel/CH101001571033.aspx" target="_blank">Macros</a> in <a href="http://office.microsoft.com/en-us/excel/FX100487621033.aspx" target="_blank">Excel 2007</a> to execute stored procedures on <a href="http://www.microsoft.com/sqlserver/2008/en/us/default.aspx" target="_blank">SQL Server</a> and provide data back to the user. These examples use the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=e719ecf7-9f46-4312-af89-6ad8702e4e6e" target="_blank">AdventureWorks</a> sample database.</p>
<p><strong>Execute a Stored Procedure with VBA</strong></p>
<p><font color="#666666">This example will execute a stored procedure that returns a resultset. The data returned will be copied to the active worksheet. First create the below stored procedure in your <a href="http://msdn.microsoft.com/en-us/library/ms124501.aspx" target="_blank">AdventureWorks</a> database.</font></p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p268code5'); return false;">View Code</a> TSQL</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p2685"><td class="code" id="p268code5"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">USE</span> <span style="color: #808080;">&#91;</span>AdventureWorks<span style="color: #808080;">&#93;</span>
GO
<span style="color: #0000FF;">SET</span> ANSI_<span style="color: #808080;">NULL</span>S <span style="color: #0000FF;">ON</span>
GO
<span style="color: #0000FF;">SET</span> QUOTED_IDENTIFIER <span style="color: #0000FF;">ON</span>
GO
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">PROCEDURE</span> <span style="color: #808080;">&#91;</span>dbo<span style="color: #808080;">&#93;</span>.<span style="color: #808080;">&#91;</span>usp_test<span style="color: #808080;">&#93;</span>
<span style="color: #0000FF;">AS</span>
&nbsp;
	<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">&#91;</span>ProductID<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>Name<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ProductNumber<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>MakeFlag<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>FinishedGoodsFlag<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>Color<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>SafetyStockLevel<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ReorderPoint<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>StandardCost<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ListPrice<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span><span style="color: #0000FF;">Size</span><span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>SizeUnitMeasureCode<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>WeightUnitMeasureCode<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>Weight<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>DaysToManufacture<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ProductLine<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span><span style="color: #0000FF;">Class</span><span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>Style<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ProductSubcategoryID<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ProductModelID<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>SellStartDate<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>SellEndDate<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>DiscontinuedDate<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>rowguid<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ModifiedDate<span style="color: #808080;">&#93;</span>
  <span style="color: #0000FF;">FROM</span> <span style="color: #808080;">&#91;</span>AdventureWorks<span style="color: #808080;">&#93;</span>.<span style="color: #808080;">&#91;</span>Production<span style="color: #808080;">&#93;</span>.<span style="color: #808080;">&#91;</span>Product<span style="color: #808080;">&#93;</span></pre></td></tr></table></div>

<p>Open up a new workbook in Excel. Next you need to add a new macro. Click the “Macros” button on the developer ribbon. N.B. You may need to <a href="http://blogs.msdn.com/erikaehrli/archive/2006/06/06/ribbondevelopertab.aspx" target="_blank">enable the Developer ribbon</a>.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image13.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Developer ribbon in Excel 2007" border="0" alt="Developer ribbon in Excel 2007" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image_thumb13.png" width="644" height="96" /></a> </p>
<p>Give the macro a name and click ‘Create’.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image14.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Creating a macro in Excel 2007" border="0" alt="Creating a macro in Excel 2007" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image_thumb14.png" width="540" height="484" /></a> </p>
<p>You will then be taken to the <a href="http://en.wikipedia.org/wiki/Visual_Basic_for_Applications" target="_blank">VBA</a> editor. Paste in the entire code below replacing what is already there. Note you will need to change the value for <strong>server</strong> in the connection string. The connection string also assumes you are using <a href="http://technet.microsoft.com/en-us/library/ms144284(SQL.90).aspx" target="_blank">Windows Authentication</a>.</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p268code6'); return false;">View Code</a> VBA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p2686"><td class="code" id="p268code6"><pre class="vba" style="font-family:monospace;">Sub execute_proc()
&nbsp;
    ' Setup connection string
    Dim connStr As String
    connStr = &quot;driver={sql server};server=localhost\sql2005;&quot;
    connStr = connStr &amp; &quot;Database=AdventureWorks;TrustedConnection=True;&quot;
&nbsp;
    ' Setup the connection to the database
    Dim connection As ADODB.connection
    Set connection = New ADODB.connection
    connection.connectionString = connStr
    ' Open the connection
    connection.Open
&nbsp;
    ' Open recordset.
    Set Cmd1 = New ADODB.Command
    Cmd1.ActiveConnection = connection
    Cmd1.CommandText = &quot;usp_test&quot;
    Cmd1.CommandType = adCmdStoredProc
    Set Results = Cmd1.Execute()
&nbsp;
    ' Clear the data from the active worksheet
    Cells.Select
    Cells.ClearContents
&nbsp;
    ' Add column headers to the sheet
    headers = Results.Fields.Count
    For iCol = 1 To headers
        Cells(1, iCol).Value = Results.Fields(iCol - 1).Name
    Next
&nbsp;
    ' Copy the resultset to the active worksheet
    Cells(2, 1).CopyFromRecordset Results
&nbsp;
End Sub</pre></td></tr></table></div>

<p>Click Tools &gt; References and scroll down the list and check “Microsoft ActiveX Data Objects 2.8 Library”.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image15.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Add a reference in Excel to the Microsoft ActiveX Data Object 2.8 Library" border="0" alt="Add a reference in Excel to the Microsoft ActiveX Data Object 2.8 Library" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image_thumb15.png" width="603" height="484" /></a> </p>
<p>Click File &gt; Close and Return to Microsoft Excel. Click the macro button on the developer ribbon. Click the run button to execute the macro.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image16.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Running a macro in Excel 2007" border="0" alt="Running a macro in Excel 2007" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image_thumb16.png" width="519" height="484" /></a> </p>
</p>
<p>If you receive the below error then you haven’t correctly added the reference mentioned above. Go back and re-add it.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image17.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Error you will get if there is no reference to the Microsoft ActiveX Data Objects 2.8 Library" border="0" alt="Error you will get if there is no reference to the Microsoft ActiveX Data Objects 2.8 Library" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image_thumb17.png" width="244" height="160" /></a> </p>
<p>If all has gone well the macro should pull some data from the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=e719ecf7-9f46-4312-af89-6ad8702e4e6e" target="_blank">AdventureWorks</a> database into the current worksheet.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image18.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Data pulled from the AdventureWorks database with an Excel macro" border="0" alt="Data pulled from the AdventureWorks database with an Excel macro" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image_thumb18.png" width="244" height="150" /></a> </p>
<p><strong>Execute a Stored Procedure with Parameters and VBA</strong></p>
<p>This example is very similar to above except this time we will execute a stored procedure that accepts an integer parameter. This parameter will be provided by the user entering a value in a popup input box.&#160; Create the below stored procedure in your <a href="http://msdn.microsoft.com/en-us/library/ms124501.aspx" target="_blank">AdventureWorks</a> database.</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p268code7'); return false;">View Code</a> TSQL</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p2687"><td class="code" id="p268code7"><pre class="tsql" style="font-family:monospace;"><span style="color: #0000FF;">USE</span> <span style="color: #808080;">&#91;</span>AdventureWorks<span style="color: #808080;">&#93;</span>
GO
<span style="color: #0000FF;">SET</span> ANSI_<span style="color: #808080;">NULL</span>S <span style="color: #0000FF;">ON</span>
GO
<span style="color: #0000FF;">SET</span> QUOTED_IDENTIFIER <span style="color: #0000FF;">ON</span>
GO
<span style="color: #0000FF;">CREATE</span> <span style="color: #0000FF;">PROCEDURE</span> <span style="color: #808080;">&#91;</span>dbo<span style="color: #808080;">&#93;</span>.<span style="color: #808080;">&#91;</span>usp_test2<span style="color: #808080;">&#93;</span>
	@ProductId <span style="color: #0000FF;">INTEGER</span>
<span style="color: #0000FF;">AS</span>
&nbsp;
	<span style="color: #0000FF;">SELECT</span> <span style="color: #808080;">&#91;</span>ProductID<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>Name<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ProductNumber<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>MakeFlag<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>FinishedGoodsFlag<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>Color<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>SafetyStockLevel<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ReorderPoint<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>StandardCost<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ListPrice<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span><span style="color: #0000FF;">Size</span><span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>SizeUnitMeasureCode<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>WeightUnitMeasureCode<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>Weight<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>DaysToManufacture<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ProductLine<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span><span style="color: #0000FF;">Class</span><span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>Style<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ProductSubcategoryID<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ProductModelID<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>SellStartDate<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>SellEndDate<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>DiscontinuedDate<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>rowguid<span style="color: #808080;">&#93;</span>
      ,<span style="color: #808080;">&#91;</span>ModifiedDate<span style="color: #808080;">&#93;</span>
  <span style="color: #0000FF;">FROM</span> <span style="color: #808080;">&#91;</span>AdventureWorks<span style="color: #808080;">&#93;</span>.<span style="color: #808080;">&#91;</span>Production<span style="color: #808080;">&#93;</span>.<span style="color: #808080;">&#91;</span>Product<span style="color: #808080;">&#93;</span>
  <span style="color: #0000FF;">WHERE</span> <span style="color: #808080;">&#91;</span>ProductID<span style="color: #808080;">&#93;</span> <span style="color: #808080;">=</span> @ProductId;</pre></td></tr></table></div>

<p>Follow the same procedure above for creating a macro but add the below code. Ensure the value for <strong>server </strong>is changed in the connection string.</p>

<div class="wp_codebox_msgheader"><span class="right"><sup><a href="http://www.ericbess.com/ericblog/2008/03/03/wp-codebox/#examples" target="_blank" title="WP-CodeBox HowTo?"><span style="color: #99cc00">?</span></a></sup></span><span class="left"><a href="javascript:;" onclick="javascript:showCodeTxt('p268code8'); return false;">View Code</a> VBA</span><div class="codebox_clear"></div></div><div class="wp_codebox"><table><tr id="p2688"><td class="code" id="p268code8"><pre class="vba" style="font-family:monospace;">Sub usp_test2()
&nbsp;
    Dim temp As String
    Dim ProductId As Integer
&nbsp;
    Do
        temp = InputBox(&quot;Enter a ProductId&quot;)
        ' Bizarrely have to check for cancel!
        If StrPtr(strwholeNo) = False Then
            Exit Sub
        End If
    Loop Until IsNumeric(temp)
&nbsp;
    'Convert the input to an integer
    ProductId = CInt(temp)
&nbsp;
    ' Setup connection string
    Dim connStr As String
    connStr = &quot;driver={sql server};server=localhost\sql2005;&quot;
    connStr = connStr &amp; &quot;Database=AdventureWorks;TrustedConnection=True;&quot;
&nbsp;
    ' Setup the connection to the database
    Dim connection As ADODB.connection
    Set connection = New ADODB.connection
    connection.connectionString = connStr
    ' Open the connection
    connection.Open
&nbsp;
    ' Open recordset.
    Set Cmd1 = New ADODB.Command
    Cmd1.ActiveConnection = connection
    Cmd1.CommandText = &quot;usp_test2 &quot; &amp; CStr(ProductId)
    Set Results = Cmd1.Execute()
&nbsp;
    ' Clear the data from the active worksheet
    Cells.Select
    Cells.ClearContents
&nbsp;
    ' Add column headers to the sheet
    headers = Results.Fields.Count
    For iCol = 1 To headers
        Cells(1, iCol).Value = Results.Fields(iCol - 1).Name
    Next
&nbsp;
    ' Copy the resultset to the active worksheet
    Cells(2, 1).CopyFromRecordset Results
&nbsp;
End Sub</pre></td></tr></table></div>

<p>A second macro called ‘usp_test2’ will appear in the Run macro dialog. Click run to execute it.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image19.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Running a stored procedure that accepts parameters with VBA" border="0" alt="Running a stored procedure that accepts parameters with VBA" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image_thumb19.png" width="519" height="484" /></a></p>
<p>You will be asked to enter a ProductId.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image20.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Provide an integer value for the procedure" border="0" alt="Provide an integer value for the procedure" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image_thumb20.png" width="244" height="102" /></a> </p>
<p>Enter a 1 and click ‘OK’. The procedure should run and return one row of data.</p>
<p><a href="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image21.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" border="0" alt="image thumb21 Practical VBA Examples for the DBA: Part 1" src="http://www.youdidwhatwithtsql.com/wp-content/uploads/2009/07/image_thumb21.png" width="244" height="150" /></a> </p>
<p>In a future article I’ll be demonstrating the use of the VBA GUI editor to create some simple user interfaces to provide better interactivity with your data.</p>
<p><map name='google_ad_map_268_a45beff5d2e172f6'>
<area shape='rect' href='http://imageads.googleadservices.com/pagead/imgclick/268?pos=0' coords='1,2,367,28' />
<area shape='rect' href='http://services.google.com/feedback/abg' coords='384,10,453,23'/></map>
<img usemap='#google_ad_map_268_a45beff5d2e172f6' border='0' src='http://imageads.googleadservices.com/pagead/ads?format=468x30_aff_img&amp;client=&amp;channel=&amp;output=png&amp;cuid=268&amp;url=http%3A%2F%2Fwww.youdidwhatwithtsql.com%2Fpractical-vba-examples-dba-part-1%2F268' title="Practical VBA Examples for the DBA: Part 1" alt=" Practical VBA Examples for the DBA: Part 1" /></p><p>Post from: <a href="http://www.youdidwhatwithtsql.com">youdidwhatwithtsql.com</a><br/><br/><a href="http://www.youdidwhatwithtsql.com/practical-vba-examples-dba-part-1/268">Practical VBA Examples for the DBA: Part 1</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.youdidwhatwithtsql.com/practical-vba-examples-dba-part-1/268/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
