Writing Code in an Excel Workbook

In this section, you will create a new Excel workbook and add code that contains errors. (The user interface might differ depending on your Visual Studio development settings. The examples in this book assume that you have chosen the Visual Basic development setting.)

1. Create a directory at the root of the C:\ drive, and name it Samples. This is the directory where you can store all the VSTO solutions described in this book.

2. Open Visual Studio 2005.

3. On the File menu, point to New and then click Project.

4. In the Project Types pane, expand the Visual Basic node and select Office.

5. Select an Excel workbook in the Templates pane, leaving the default name (ExcelWorkbookl if this is your first Excel project), and then click OK to create a new workbook project.

6. In the Visual Studio Tools for Office Project Wizard, select Create a New Document and then click OK.

7. Right-click the project in Solution Explorer, and click View Code.

8. Create a BeforeDoubleClick event handler by selecting Sheetl Events in the Class Name drop-down and then selecting BeforeDoubleClick in the Method Name drop-down.

9. Add the code in Listing 2.1 to the BeforeDoubleClick event handler of Sheetl.

Listing 2.1. Code that raises an exception

Private Sub Sheet1_BeforeDoubleClick(ByVal Target As _ Microsoft.Office.Interop.Excel.Range, _ ByRef Cancel As Boolean) Handles Me.BeforeDoubleClick

Dim myString As Object = Nothing MsgBox(myString.ToString) myString = "This is a test" MsgBox(myString.ToString)

End Sub

10. Save the solution to the Samples directory at the root of the C:\ drive.

11. Run the code by pressing F5.

The code is built and the application opens. When you double-click Sheetl, the exception that should occur when you try to convert a null variable to a string is swallowed by the debugger, and no error is displayed in a message box. By default, Visual Studio does not display errors that are thrown by Microsoft Office 2003 applications. This is why it's important to set the debugging options correctly before you start debugging your application.

0 0

Post a comment