This topic has not yet been rated - Rate this topic

How to: Automate Objects Using Managed Code

When you write managed code, by default you must specify an object's type. However, many Office object model methods and properties return the type Object, because they have the capability to return several different types. When the object is returned, you must explicitly convert (in Visual Basic) or cast (in C#) the object to the correct type. Converting or casting the object enables IntelliSense for the object in the code editor.

For information on conversion in Visual Basic, see Implicit and Explicit Conversions and CType Function. For information on casting in C#, see () Operator.

The following procedure is an example of casting an object returned by Office to a specific type for use in managed code.

To cast an object to a specific type

  1. Add a NamedRange control to cell A1.

    Microsoft.Office.Tools.Excel.NamedRange NamedRange1 = 
        this.Controls.AddNamedRange(this.Range["A1", missing], "NamedRange1");
    
    
  2. Cast the object returned from the column width of the named range to a double and assign it to a variable.

    double width = (double)NamedRange1.ColumnWidth;
    
    
  3. Display the column width of the NamedRange control in a dialog box.

    MessageBox.Show("Column width: " + width.ToString());
    
    

See Also

Did you find this helpful?
(1500 characters remaining)

Community Additions

ADD
© 2013 Microsoft. All rights reserved.