Receive new articles directly in your inbox!! Register your email address
Learn how to create dynamic Excel dashboards with VBA. Build pivot tables and create graphs using VBA code.
Excel dashboards are powerful tools for visualizing and analyzing data.
For intermediate VBA users, automating the creation of these dashboards can save time and enhance accuracy.
In this article, we’ll walk you through the process of building an Excel dashboard using VBA, focusing on creating pivot tables, adding custom measures, and generating graphs.
By the end of this post, you'll be able to create a dynamic dashboard that updates with your data.
To illustrate, let's use a dataset containing sales data across different regions.
We will create a dashboard that shows total sales, average sales per region, and a sales trend graph over time.
Assume we have an Excel table named 'SalesData' with the following columns
Date
Region
Product
Sales
Here is a sample of the data
Pivot tables are essential for summarizing large datasets.
We will write VBA code to create a pivot table that shows total sales by region.
Overview:
Define the data range.
Create a PivotCache.
Insert a PivotTable.
Sub CreatePivotTable()
Dim ws As Worksheet
Dim pc As PivotCache
Dim pt As pivotTable
Dim datarange As Range
Set ws = ThisWorkbook.Sheets("Sheet1")
Set datarange = ws.Range("A1:D6")
Set pc = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=datarange)
Set pt = pc.CreatePivotTable(TableDestination:=ws.Range("F10"), TableName:="SalesPivot")
With pt
.PivotFields("Region").Orientation = xlRowField
.PivotFields("Sales").Orientation = xlDataField
.PivotFields("Sales").NumberFormat = "$#,##0"
End With
End Sub
This is how the newly generated Pivot Table looks like
Graphs are crucial for visualizing data trends. We'll create a sales trend graph using VBA.
Overview:
Define the chart range.
Create and format the chart.
Sub CreateSalesTrendChart()
Dim ws As Worksheet
Dim chartObj As ChartObject
Set ws = ThisWorkbook.Sheets("Sheet1")
Set chartObj = ws.ChartObjects.Add(Left:=100, Width:=375, Top:=50, Height:=225)
With chartObj.Chart
.SetSourceData Source:=ws.Range("A2:A6, D2:D6")
.ChartType = xlLine
' Formatting the chart
.HasTitle = True
.ChartTitle.Text = "Sales Trend Over Time"
.Axes(xlCategory).HasTitle = True
.Axes(xlCategory).AxisTitle.Text = "Date"
.Axes(xlValue).HasTitle = True
.Axes(xlValue).AxisTitle.Text = "Sales ($)"
End With
End Sub
This is how the end result looks like
We explored how to create dynamic Excel dashboards using VBA.
We covered setting up your environment, creating pivot tables and building graphs.
By automating these tasks with VBA, you can create powerful and dynamic dashboards that update seamlessly with your data.
Start implementing these techniques today to enhance your Excel data visualization capabilities.