Excel VSTO AddIn – 从select中获取图表对象

我将如何将用户的select转换为VSTO Excel加载项中的图表对象(如Excel.Chart )。

我一直在尝试使用这样的东西(同时在Excel中select一个图表对象):

Dim chart as Excel.Chart = CType(Globals.ThisAddIn.Application.Selection, Excel.Chart)

但是,这会引发InvalidCastException

我似乎无法find任何有关如何让用户select图表,然后在VSTO加载项中修改所选图表的文档。

您的代码需要确定select是否实际包含Chart对象,然后从中派生Chart。 为了确定Selection包含什么,当使用VB.NET时,使用返回String的TypeName方法,然后计算string:

 Public Function IsSelectionChart() as Boolean Dim cht As Excel.Chart Dim sSelectionType As String Dim xlApp As Excel.Application = Globals.ThisAddIn.Application sSelectionType = TypeName(xlApp.Selection) Select Case sSelectionType Case "ChartArea", "PlotArea", "Legend" cht = xlApp.Selection.Parent Debug.Print(cht.Name) Case "Series" cht = xlApp.Selection.Parent.Parent Debug.Print(cht.Name) Case "Axis" 'Parent is Worksheet Debug.Print("Can't determine the chart from an Axis") Case Else Debug.Print("Not a chart-related object") End Select If Not cht Is Nothing Then Return True Else Return False End If End Function