This example illustrates the creation of a comprehensive Excel® add-in to perform spectral analysis. It requires knowledge of Visual Basic® forms and controls, and Excel workbook events. See the VBA documentation for a complete discussion of these topics.
You create an Excel add-in that performs a fast Fourier transform (FFT) on an input data set located in a designated worksheet range. The function returns the FFT results, an array of frequency points, and the power spectral density of the input data. It places these results into ranges you indicate in the current worksheet. You can also optionally plot the power spectral density.
You develop the function so that you can invoke it from the Excel Tools menu and can select input and output ranges through a UI.
To create the add-in:
Build a standalone COM component from the MATLAB® code.
Implement the necessary VBA code to collect input and dispatch the calls to your component.
Create the UI.
Create an Excel add-in, and package all necessary components for application deployment.
Your component has one class with two methods:
computefft — Compute the FFT and power spectral
density of the input data, and compute a vector of frequency points based on the
length of the data entered and the sampling interval.
plotfft — Perform the same operations as
computefft, but also plot the input data and the power
spectral density in a MATLAB Figure window.
Note
The MATLAB code for these two functions is in two MATLAB files, computefft.m and plotfft.m.
The code for computefft.m:
function [fftdata, freq, powerspect] =
computefft(data, interval)
if (isempty(data))
fftdata = [];
freq = [];
powerspect = [];
return;
end
if (interval <= 0)
error('Sampling interval must be greater than zero');
return;
end
fftdata = fft(data);
freq = (0:length(fftdata)-1)/(length(fftdata)*interval);
powerspect = abs(fftdata)/(sqrt(length(fftdata)));
The code for plotfft.m.m:
function [fftdata, freq, powerspect] = plotfft(data, interval)
[fftdata, freq, powerspect] = computefft(data, interval);
len = length(fftdata);
if (len <= 0)
return;
end
t = 0:interval:(len-1)*interval;
subplot(2,1,1), plot(t, data)
xlabel('Time'), grid on
title('Time domain signal')
subplot(2,1,2), plot(freq(1:len/2), powerspect(1:len/2))
xlabel('Frequency (Hz)'), grid on
title('Power spectral density')Build the COM component using the Library Compiler app and these settings:
| Setting | Value |
|---|---|
| Component name | Fourier |
| Class name | Fourier |
| Project folder | Name of your work folder, followed by the component name |
| Show verbose output | Selected |
For more information, see the instructions in Create Excel Add-In from MATLAB.
For more information about accessing the example code from within the product ,see Example File Copying.
Having built your component, you can implement the necessary VBA code to integrate it into Excel.
Note
To use Fourier.xla directly in the folder
xlspectral, (see Example File Copying) add references to Fourier 1.0 Type
Library and MWComUtil 7.X Type
Library.
To open Excel and select the libraries, you should develop the add-in:
Start Excel on your system.
From the Excel main menu, select Tools > Macro > Visual Basic Editor.
In the Visual Basic Editor, select Tools > References to open the Project References dialog box.
Select Fourier 1.0 Type Library and MWComUtil 7.x Type Library.
Create the Main VB Code Module for the Application. The add-in requires initialization code and global variables to hold the application state between function invocations. To achieve this, implement a Visual Basic code module to manage these tasks:
Right-click the VBAProject item in the project window and select Insert > Module.
A new module appears under Modules in the VBA Project.
In the module property page, set the
Name property to
FourierMain.
Enter the following code in the
FourierMain module:
'
' FourierMain - Main module stores global state of controls
' and provides initialization code
'
Public theFourier As Fourier.Fourier 'Global instance of Fourier object
Public theFFTData As MWComplex 'Global instance of MWComplex to accept FFT
Public InputData As Range 'Input data range
Public Interval As Double 'Sampling interval
Public Frequency As Range 'Output frequency data range
Public PowerSpect As Range 'Output power spectral density range
Public bPlot As Boolean 'Holds the state of plot flag
Public theUtil As MWUtil 'Global instance of MWUtil object
Public bInitialized As Boolean 'Module-is-initialized flag
Private Sub LoadFourier()
'Initializes globals and Loads the Spectral Analysis form
Dim MainForm As frmFourier
On Error GoTo Handle_Error
Call InitApp
Set MainForm = New frmFourier
Call MainForm.Show
Exit Sub
Handle_Error:
MsgBox (Err.Description)
End Sub
Private Sub InitApp()
'Initializes classes and libraries. Executes once
'for a given session of Excel
If bInitialized Then Exit Sub
On Error GoTo Handle_Error
If theUtil Is Nothing Then
Set theUtil = New MWUtil
Call theUtil.MWInitApplication(Application)
End If
If theFourier Is Nothing Then
Set theFourier = New Fourier.Fourierclass
End If
If theFFTData Is Nothing Then
Set theFFTData = New MWComplex
End If
bInitialized = True
Exit Sub
Handle_Error:
MsgBox (Err.Description)
End SubDevelop a user interface for your add-in using the Visual Basic Editor. To create a new user form and populate it with the necessary controls:
Right-click VBAProject in the VBA project window, and select Insert > UserForm.
A new form appears under Forms in the VBA project
window.
In the form property page, set the
Name property to frmFourier and
the Caption property to Spectral
Analysis.
Add a series of controls to the blank form:
Controls for Spectral Analysis
| Control Type | Control Name | Properties | Purpose |
|---|---|---|---|
|
| Caption = | Plot input data and power spectral density. |
|
| Caption = Default = True | Execute the function and dismiss the dialog box. |
|
| Caption =
Cancel = True | Dismisse the dialog box without executing the function. |
|
| Caption = | Group all input controls. |
|
| Caption = | Group all output controls. |
|
| Caption = | Label the |
TextBox | edtSample | Not applicable | Not applicable |
|
| Caption = | Label the |
|
| Caption =
| Label the |
|
| Caption = | Label the |
|
| Caption = | Label the |
|
| Caption = | Label the |
|
| Not applicable | Select range for input data. |
|
| Not applicable | Select output range for frequency points. |
|
| Not applicable | Select output range for real part of FFT of input data. |
|
| Not applicable | Select output range for imaginary part of FFT of input data. |
|
| Not applicable | Select output range for power spectral density of input data. |
When the form and controls are complete, right-click the form, and select View code.
The following code listing shows the code to implement. Notice that this code references the control and variable names listed in Controls for Spectral Analysis. If you used different names for any of the controls or any global variable, change this code to reflect those differences.
'
'frmFourier Event handlers
'
Private Sub UserForm_Activate()
'UserForm Activate event handler. This function gets called before
'showing the form, and initializes all controls with values stored
'in global variables.
On Error GoTo Handle_Error
If theFourier Is Nothing Or theFFTData Is Nothing Then Exit Sub
'Initialize controls with current state
If Not InputData Is Nothing Then
refedtInput.Text = InputData.Address
End If
edtSample.Text = Format(Interval)
If Not Frequency Is Nothing Then
refedtFreq.Text = Frequency.Address
End If
If Not IsEmpty (theFFTData.Real) Then
If IsObject(theFFTData.Real) And TypeOf theFFTData.Real Is Range Then
refedtReal.Text = theFFTData.Real.Address
End If
End If
If Not IsEmpty (theFFTData.Imag) Then
If IsObject(theFFTData.Imag) And TypeOf theFFTData.Imag Is Range Then
refedtImag.Text = theFFTData.Imag.Address
End If
End If
If Not PowerSpect Is Nothing Then
refedtPowSpect.Text = PowerSpect.Address
End If
chkPlot.Value = bPlot
Exit Sub
Handle_Error:
MsgBox (Err.Description)
End Sub
Private Sub btnCancel_Click()
'Cancel button click event handler. Exits form without computing fft
'or updating variables.
Unload Me
End Sub
Private Sub btnOK_Click()
'OK button click event handler. Updates state of all variables from controls
'and executes the computefft or plotfft method.
Dim R As Range
If theFourier Is Nothing Or theFFTData Is Nothing Then GoTo Exit_Form
On Error Resume Next
'Process inputs
Set R = Range(refedtInput.Text)
If Err <> 0 Then
MsgBox ("Invalid range entered for Input Data")
Exit Sub
End If
Set InputData = R
Interval = CDbl(edtSample.Text)
If Err <> 0 Or Interval <= 0 Then
MsgBox ("Sampling interval must be greater than zero")
Exit Sub
End If
'Process Outputs
Set R = Range(refedtFreq.Text)
If Err = 0 Then
Set Frequency = R
End If
Set R = Range(refedtReal.Text)
If Err = 0 Then
theFFTData.Real = R
End If
Set R = Range(refedtImag.Text)
If Err = 0 Then
theFFTData.Imag = R
End If
Set R = Range(refedtPowSpect.Text)
If Err = 0 Then
Set PowerSpect = R
End If
bPlot = chkPlot.Value
'Compute the fft and optionally plot power spectral density
If bPlot Then
Call theFourier.plotfft(3, theFFTData, Frequency, PowerSpect, _
InputData, Interval)
Else
Call theFourier.computefft(3, theFFTData, Frequency, PowerSpect, _
InputData, Interval)
End If
GoTo Exit_Form
Handle_Error:
MsgBox (Err.Description)
Exit_Form:
Unload Me
End SubAdd a menu item to Excel so that you can open the tool from the Excel
Tools menu. To do this, add event handlers for the
workbook events AddinInstall and
AddinUninstall that install and uninstall menu items. The
menu item calls the LoadFourier function in the
FourierMain module.
To implement the menu item:
Right-click the ThisWorkbook item in the VBA project window, and select View code.
Place the following code into ThisWorkbook.
Private Sub Workbook_AddinInstall()
'Called when Addin is installed
Call AddFourierMenuItem
End Sub
Private Sub Workbook_AddinUninstall()
'Called when Addin is uninstalled
Call RemoveFourierMenuItem
End Sub
Private Sub AddFourierMenuItem()
Dim ToolsMenu As CommandBarPopup
Dim NewMenuItem As CommandBarButton
'Remove if already exists
Call RemoveFourierMenuItem
'Find Tools menu
Set ToolsMenu = Application.CommandBars(1).FindControl(ID:=30007)
If ToolsMenu Is Nothing Then Exit Sub
'Add Spectral Analysis menu item
Set NewMenuItem = ToolsMenu.Controls.Add(Type:=msoControlButton)
NewMenuItem.Caption = "Spectral Analysis..."
NewMenuItem.OnAction = "LoadFourier"
End Sub
Private Sub RemoveFourierMenuItem()
Dim CmdBar As CommandBar
Dim Ctrl As CommandBarControl
On Error Resume Next
'Find tools menu and remove Spectral Analysis menu item
Set CmdBar = Application.CommandBars(1)
Set Ctrl = CmdBar.FindControl(ID:=30007)
Call Ctrl.Controls("Spectral Analysis...").Delete
End SubSave the add-in into the
<project-folder>\for_testing.
<project-folder> refers to the project folder
that Library Compiler used to save the Fourier project.
Name the add-in Spectral Analysis.
From the Excel main menu, select File > Properties.
In the Workbook Properties dialog box, click the
Summary tab, and enter
Spectral Analysis as the workbook
title.
Click OK to save the edits.
From the Excel main menu, select File > Save As.
In the Save As dialog box, select Microsoft Excel Add-In
(*.xla) as the file type, and browse to
<project-folder>\for_testing.
Enter Fourier.xla as the file name, and click
Save.
Before distributing the add-in, test it with a sample problem. Spectral analysis is commonly used to find the frequency components of a signal buried in a noisy time domain signal. Create a data representation of a signal containing two distinct components, and add to it a random component. This data along with the output is stored in columns of an Excel worksheet, and you plot the time-domain signal along with the power spectral density.
Start a new session of Excel with a blank workbook.
From the main menu, select Tools > Add-Ins.
In the Add-Ins dialog box, click Browse.
Browse to the <project-folder>\for_testing folder,
select Fourier.xla, and click OK.
The Spectral Analysis add-in appears in the available Add-Ins list and is selected.
Click OK to load the add-in.
This add-in installs a menu item under the Excel Tools menu. To display the Spectral Analysis UI, select Tools > Spectral Analysis. Before invoking the add-in, create some data, in this case a signal with components at 15 Hz and 40 Hz. Sample the signal for 10 seconds at a sampling rate of 0.01 s. Put the time points into column A and the signal points into column B.
Enter 0 for cell A1 in
the current worksheet.
Click cell A2, and type the formula "= A1 +
0.01".
Click and hold the lower-right corner of cell A2 and drag the formula down the column to cell A1001. This procedure fills the range A1:A1001 with the interval 0–10 incremented by 0.01.
Click cell B1, and type the following formula
"= SIN(2*PI()*15*A1) + SIN(2*PI()*40*A1) +
RAND()"
Repeat the drag procedure to copy this formula to all cells in the range B1:B1001.
Using the column of data (column B), test the add-in as follows:
Select Tools > Spectral Analysis from the main menu.
Click the Input Data box.
Select the B1:B1001 range
from the worksheet, or type this address into the Input
Data field.
In the Sampling Interval field,
type 0.01.
Select Plot time domain signal and power spectral density.
Enter C1:C1001 for frequency output,
and likewise enter D1:D1001, E1:E1001,
and F1:F1001 for the FFT real and imaginary parts,
and spectral density.
Click OK to run the analysis.
The next figure shows the output.

The power spectral density reveals the two signals at 15 Hz and 40 Hz.
Package the add-in, the COM component, and all supporting libraries into a self-extracting
executable. This package can be installed on other computers that use the
Spectral Analysis add-in.
On the Main File section of the toolstrip, choose one of these two options.
| Option | What Does This Option Do? | When Should I Use This Option? |
|---|---|---|
| Runtime downloaded from web | The MATLAB Runtime installer downloads the MATLAB Runtime from the MathWorks website. |
|
| Runtime included in package | The MATLAB Runtime is included in the generated installer, which uses the included MATLAB Runtime. |
|
Add others files that would be useful to end users.
To package additional files or folders, add them to the Files installed for your end user field. See Specify Files to Install with Application.
Click Package.
To install this add-in on another computer, copy the Fourier_pkg.exe
package to that machine, run it from a command prompt, and follow the instructions in
the GettingStarted.html file that is automatically generated with
your packaged output.