Simplify management of an Excel Power View template by using a VSTO add-in

Today’s tutorial is brought to us by MVP Dennis Wallentin, who has been developing Excel business solutions since the 1980s. He is the founder of XL-Dennis, author of various articles for MSDN and Swedish technology publications, and co-author of an Excel textbook.

One of the cornerstones in modern professional Excel development is the use of templates. By using one or more templates, we provide a structural approach for end users to acquire, store and present data. From a development point of view, the major advantage is that we simplify the maintenance.

The focus for the article is to show how we can simplify management of a Power View template by using a VSTO add-in.

What is Power View?

New versions of Excel today are equivalent to new tools for Business Intelligence (BI) Self-Service. The background is that we now work more and more with larger data sets, and to derive insights, new forms of reports become necessary. With Excel 2010, the Power Pivot tool was released. Now with Excel 2013, the Power View tool was released.

In summary, Power View is:

  • A new BI Self-Service design tool.
  • Very helpful in creating interactive reports.
  • Useful for both ad hoc reports as well as part of more structured reporting systems.
  • A light-weighted design tool relative to PP.
  • Able to use PP as a data source for its reports, among other data sources.

Before going in to detail to discuss Power View itself, let me point out that both these two tools have been successfully implemented in Microsoft SQL Server and Microsoft SharePoint before they were released in Excel. In other words, Power View is well-tested and reliable.

Power View is an add-in shipped with Excel 2013. To activate it:

  1. Select the DEVELOPER tab.
  2. Click the COM Add-ins button.
  3. Check the option Power View as the following screenshot shows:

When Power View is activated we can find its button under the INSERT tab as the below screenshot also shows:

When we click the Power View button, Excel 2013 creates a new blank Power View Report sheet, as pictured below:

When we have filled the Power View Report sheet with data and the list is selected, a new Ribbon tab is available. The following screenshot shows its contents:

The data

The data we will be using for this example is originally stored in a SQL Server 2012 database. The user, XL-Dennis, has restricted access to the database’s production data. In order to retrieve the data we use the following connection string:

“Data Source=DenWal;Initial Catalog=AdventureWorks2012;User ID=XLDennis;Password=secret”

The VSTO add-in

The VSTO add-in we will be using in this context serves two purposes: to open a copy of the Template Workbook and to populate its worksheet with data.

Creating the VSTO add-in is an easy process:

  1. Start Microsoft Visual Studio 2012.
  2. On the Start Page, select the option New Project.
  3. In the left column in the dialog, navigate via Installed > Templates > Visual Basic > Office/SharePoint > Office Add-ins.
  4. Select the Excel 2013 add-in template and name it PVData.

As you can see, the VSTO add-in template uses version 4.5 of the .NET Framework.

The VSTO add-in template sets references to several classes, including the Interop Office and Excel classes as well as the VSTO classes, which the following screenshot shows:

The VSTO add-in template also creates the list of prerequisites in order to run the created add-in:

If we need to add prerequisites for Office 2013 primary interop assemblies (PIA) then the following blog entry is of interest: Creating a Bootstrapper package for an Office 2013 VSTO Add-in with Visual Studio 2012.

The next step is to add a Ribbon UI control to the VSTO add-in:

  1. Select the command PROJECT from the main menu.
  2. Select the command Add User Control
  3. In the dialog, select Ribbon (Visual Design)
  4. Name it PVRibbon.vb

How we design the Ribbon UI controls are beyond this article’s scope. However, a great source for more information is: Microsoft’s Guidelines for Ribbon UI.

The following screenshot shows the design of the VSTO add-ins Ribbon UI:

Since the solution does not require a lot of controls, it is better to place it on the built-in tab Add-ins.

In this case we use the Buttons click events to execute the code. The list below shows the code for each button:

Imports Microsoft.Office.Tools.Ribbon

Imports System.Windows.Forms


Public Class PVRibbon



    Dim cPVData As New cPV


    Private Sub PVRibbon_Load(ByVal sender As System.Object, ByVal e As RibbonUIEventArgs) Handles MyBase.Load


    End Sub


    Private Sub btnHelp_Click(sender As Object, e As RibbonControlEventArgs) Handles btnHelp.Click




        Catch ex As Exception

            MessageBox.Show(“The Help file could not be found!”)

        End Try


    End Sub


    Private Sub btnReport_Click(sender As Object, e As RibbonControlEventArgs) Handles btnReport.Click



            If cPVData.Load_Report = True Then


            End If

        Catch ex As Exception

            MessageBox.Show(“Cannot load the Template file!”)

        End Try


    End Sub


    Private Sub btnData_Click(sender As Object, e As RibbonControlEventArgs) Handles btnData.Click


        ‘Check to make sure we are working with the right workbook.

        If Globals.ThisAddIn.Application.ActiveWorkbook.Name Like “PVData*” Then


                If cPVData.Acquire_Data() = True Then


                End If

            Catch ex As Exception


            End Try


            MessageBox.Show(“Please make sure that the PVData workbook is the active workbook.”)

        End If


    End Sub


End Class

As we can see from the code we use a class module, cPV.vb, that includes the function procedures. The cPV.vb class module holds the key function procedures:

Imports System.Data

Imports System.Data.SqlClient

Imports System.Text


Public Class cPV


    ‘Connection string for the SQL MS Server 2012.

    ‘Of course, this information should be stored in a variable in the solution’s Settings.

    Const DBConnection As String = “Data Source=DenWal;Initial Catalog=AdventureWorks2012;User ID=XLDennis;Password=street”


    Friend Sub Load_Help()

        ‘Not implemented.

    End Sub


    Friend Function Load_Report() As Boolean


        Dim BFlag As Boolean = False



            ‘Open a new copy of the PV Data Template.


            ‘If things worked out as expected we set the flag to True.

            BFlag = True

        Catch ex As Exception


        End Try


        Return BFlag


    End Function



    Friend Function Acquire_Data() As Boolean


        ‘Two Interop variables are created.

        Dim WBData As Excel.Workbook = Globals.ThisAddIn.Application.ActiveWorkbook

        Dim WSData As Excel.Worksheet = CType(WBData.Worksheets(“Data”), Global.Microsoft.Office.Interop.Excel.Worksheet)


        ‘Create the SQL Expression

        Dim SQLExpress As New StringBuilder

        SQLExpress.Append(“Select “)

        SQLExpress.Append(“Production.ProductSubcategory.Name As [Product Category], “)

        SQLExpress.Append(“Production.Product.Name As [Product Name], “)

        SQLExpress.Append(“Sum(Production.WorkOrder.StockedQty) As [Stocked Quantity], “)

        SQLExpress.Append(“Sum(Production.WorkOrder.ScrappedQty) As [Scrapped Quantity], “)

        SQLExpress.Append(“Sum(Production.WorkOrder.OrderQty) As [Order Quantity] “)

        SQLExpress.Append(“From “)

        SQLExpress.Append(“Production.Product Inner Join “)

        SQLExpress.Append(“Production.WorkOrder On Production.WorkOrder.ProductID = “)

        SQLExpress.Append(“Production.Product.ProductID Inner Join “)

        SQLExpress.Append(“Production.ProductSubcategory On Production.Product.ProductSubcategoryID = “)

        SQLExpress.Append(“Production.ProductSubcategory.ProductSubcategoryID Inner Join “)

        SQLExpress.Append(“Production.ProductCategory On Production.ProductSubcategory.ProductCategoryID= “)

        SQLExpress.Append(“Production.ProductCategory.ProductCategoryID “)

        SQLExpress.Append(“Group By “)

        SQLExpress.Append(“Production.ProductSubcategory.Name, Production.Product.Name “)

        SQLExpress.Append(“Order By “)

        SQLExpress.Append(“Production.ProductSubcategory.Name, “)



        ‘Open the database

        Dim SQLCon As New SqlConnection(DBConnection)



        ‘Create a DataAdapter.

        Dim SQLDa As New SqlDataAdapter(SQLExpress.ToString, SQLCon)

        ‘Create a new DataSet.

        Dim SQLDs As New DataSet


        ‘Populate the DataSet with the acquired data.

        SQLDa.Fill(SQLDs, “PVData”)


        ‘Shut down the connection.



        ‘This ‘convert’ a Interop worksheet to a Tools worksheets so its functionality is extended.

        ‘It allows us to create and place a ListObject control to the worksheet.

        Dim VSTOWorksheet As Microsoft.Office.Tools.Excel.Worksheet = Globals.Factory.GetVstoObject(WSData)


        ‘Prevent the screen from flickering during the execution.

        Globals.ThisAddIn.Application.ScreenUpdating = False


        ‘Remove previously data columns.



        ‘Create a new ListObject control.

        Dim MYList As Microsoft.Office.Tools.Excel.ListObject = _

            VSTOWorksheet.Controls.AddListObject(WSData.Range(“A1”), “MYList”)


        With MYList

            ‘Add the field names from the data source to the first row in the ListObject.

            .AutoSetDataBoundColumnHeaders = True

            ‘Here we bind the data source to the ListObject.

            .DataSource = SQLDs.Tables(0).DefaultView

            ‘If we want to make the table viewable.


            ‘Example of formatting the data.

            .DataBoundFormat = Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1

            ‘Disconnect the ListObject from its datasource.


            ‘Convert the ListObject to a basic table.


        End With


        ‘Restore the ScreenUpdating. Unlike when working with VBA we must explicit turn it on.

        ‘In a real world solutions this must be part of an error handling.

        Globals.ThisAddIn.Application.ScreenUpdating = True


        ‘Cleaning up.





        SQLDs = Nothing

        SQLDa = Nothing

        SQLCon = Nothing



        Return True


    End Function



End Class

When executing the code we first get a copy of the Template Workbook. Next, the worksheet is populated with the required data.

The template workbook

To create the template workbook, it is initially quite easy.

  1. We save a native workbook in file format XLTX and name it PVData.
  2. Next we name a worksheet Data.
  3. Remove the other sheets from the workbook.

Now, we’ll do some additional manual steps before the Template Workbook is completed and can be used. (Note: There isn’t access to APIs to work with the Power View in code). We need to first load the VSTO add-in, add some data to the data worksheet and add a Power View Report sheet.

  1. Make sure that the VSTO add-in PVData.dll is loaded and accessible when starting Excel.
  2. Open the original template workbook PVData.xltx. Before opening it, make sure to hold down the Shift button. Otherwise only a copy is created of the template workbook.
  3. Select the data sheet, then click the Acquire Data button.
  4. Add a Power View Report sheet to the workbook by clicking the Power View button on the Ribbon and save the workbook.

We now should see a window similar to the following screenshot:

Power View is a flexibly designed reporting tool with many design alternatives. Here, we are pleased with the basic design so the last action is to save the template workbook.

We can remove the data from the data worksheet before saving the template workbook. The Power View Report design we have made is not affected, so save and close the workbook.

Some final notes

In a production environment, pathways should not be hard-coded.

Excel 2013 is now Single Document Instance (SDI) software, meaning that each workbook opens in its own window, similar to Microsoft Word. Previous versions of Excel were all Multi Document Interface, meaning that all workbooks shared one window. The impact of this change for a solution like our PVData file is:

  1. When clicking the Open Report button in the Ribbon in Excel, a new window opens with a copy of the template workbook.
  2. Activate the new window and click the Acquire Data button to populate the data worksheet.

In summary, by using this add-in and the built-in functionality in Excel, you have an efficient and effective approach, especially when compared to other options.  

Note: Proper versions of the product are required. Power View is only available with Pro Plus.

Dennis Wallentin

More about the author

Dennis Wallentin is located in Östersund, Sweden. Dennis has been developing Excel business solutions since the 1980s, and he has a Master’s degree in business management and accounting. He is the founder of XL-Dennis, which delivers solutions for all sizes of companies including the public sector both in Sweden and internationally. He co-authored the 2nd Edition of Professional Excel Development, published by Addison-Wesley Professional in 2009. He has also written Excel articles for MSDN and for Swedish computer magazines. His focus is on creating Excel business solutions based on .NET technologies, including Visual Studio Tools for Office System (VSTO). Since 2010, Dennis is honored to be part of Microsoft’s Most Valuable Professional (MVP) program for Excel.