Accessing an Interop Object from a Host Control

Sometimes you need to access the Interop object associated with a given host control. For example, you might be working with the host controls and want to call a method that specifically requires an Interop object. You cannot cast a VSTO object into an Interop object, but you can instead call the InnerObject property of the host control to return its underlying Interop object.

For example, if you wanted to write a solution that enables users to add a NamedRange control to the worksheet by clicking a button on the actions pane, you need to identify the active worksheet and then add the NamedRange control to it. The problem is that the ActiveWorksheet property returns an Interop worksheet, and to add a control to a worksheet you must reference a VSTO worksheet. The answer is to use the InnerObject property of a VSTO worksheet to determine whether it is equivalent to the ActiveSheet. The example in Listing 7.18 checks whether the active worksheet is Sheet1 and, if it is, adds a named range to Sheet1. You could expand this code by comparing the ActiveSheet to Sheet2 and Sheet3.

Listing 7.18. Using the InnerObject property

Dim CurrentRange As Microsoft.Office.Interop.Excel.Range = _ Application.Selection

Dim NamedRangeCount As Integer = Application.Names.Count

If Globals.ThisWorkbook.ActiveSheet.Equals( _ Globals.Sheet1.InnerObject) Then

Globals.Sheet1.Controls.AddNamedRange( _

CurrentRange, "NamedRange" & NamedRangeCount + 1)

End If

0 0

Post a comment