Main Content

Display Message for Workbook OnClose Event

This example shows how to handle a COM interface event, how to set up an event in a Microsoft® Excel® workbook object, and how to handle its BeforeClose event.

Create the following event handler file, OnBeforeCloseWorkbook.m, in your current folder.

function OnBeforeCloseWorkbook(varargin)
disp('BeforeClose event occurred')

Create the Excel object and make it visible.

xl = actxserver('Excel.Application');
xl.Visible = 1;

Add a workbook.

hWbks = xl.Workbooks;
hWorkbook = hWbks.Add;

Register the OnBeforeCloseWorkbook function for the OnClose event.

registerevent(hWorkbook,{'BeforeClose' @OnBeforeCloseWorkbook})

Close the workbook, which triggers the Close event and calls the OnClose handler.

Close(hWorkbook)
BeforeClose event occurred
Quit(xl)

See Also

Related Topics