Section 5.2.Create .NET Components


5.2. Create .NET Components

If you are an experienced VBA programmer, this is a great way to start learning .NET because you can take advantage of features built in to the .NET Framework in small, incremental steps.


Note: You can use .NET components from any VBA application. There are no version restrictions and no prerequisites other than the .NET Framework.

5.2.1. How to do it

To create a .NET component for use in Excel:

  1. From within Visual Studio .NET, create a new Class Library project using VB.NET or C#. Visual Studio creates a folder and template files for the project as shown in Figure 5-1.

    Figure 5-1. A new, empty .NET class library project


  2. From the Project menu, choose Add Class. Visual Studio displays the Add Project Item dialog box, as shown in Figure 5-2.

    Figure 5-2. Create a new COM class to contain components for use from Excel


  3. Give the new class a descriptive name and click OK. Visual Studio registers the project to interoperate with COM (the Register for COM Interop selection on the Project Options, Build dialog box) and creates a new, empty code template for your class, as shown in Figure 5-3.

  4. Add code to the class library for the objects, properties, and methods you want to use from Excel.

  5. Compile the project by selecting Build Solution from the Build menu. Visual Studio builds the class library as a .NET assembly (.dll) and creates a type library file (.tlb) that allows Excel and other COM applications to use that assembly. Both of these files are placed in a /bin folder within the project folder created in Step 1.

For example, the NetForExcel project (NetForExcel.sln) includes a simple class that provides a single method, which displays a message passed in as an argument:

    ' .NET code.    Public Class NetObject        Public Sub Test(ByVal arg As String)            MsgBox(arg)        End Sub    End Class

Figure 5-3. The COM class code template contains the basic elements you need for a component


5.2.2. What about...

The next section shows you how to use this sample .NET component from within Excel.



    Excel 2003 Programming. A Developer's Notebook
    Excel 2003 Programming: A Developers Notebook (Developers Notebook)
    ISBN: 0596007671
    EAN: 2147483647
    Year: 2004
    Pages: 133
    Authors: Jeff Webb

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net