Excel VSTO 加载项 - 从选择中获取图表对象
Excel VSTO AddIn - Get Chart Object from Selection
我如何将用户的 selection 投射到 Excel.
的 VSTO 加载项中的图表对象(类似于 Excel.Chart
)
我一直在尝试使用这样的东西(同时在 Excel 中 select 编辑了一个图表对象):
Dim chart as Excel.Chart = CType(Globals.ThisAddIn.Application.Selection, Excel.Chart)
但是,这会引发 InvalidCastException
。
我似乎找不到任何关于如何允许用户 select 图表然后在 VSTO 加载项中修改 selected 图表的文档。
您的代码需要确定 Selection 是否实际包含 Chart 对象,然后从中派生 Chart。为了确定一个 Selection 包含什么,在使用 VB.NET 时使用 TypeName 方法,其中 returns 一个 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
我如何将用户的 selection 投射到 Excel.
的 VSTO 加载项中的图表对象(类似于Excel.Chart
)
我一直在尝试使用这样的东西(同时在 Excel 中 select 编辑了一个图表对象):
Dim chart as Excel.Chart = CType(Globals.ThisAddIn.Application.Selection, Excel.Chart)
但是,这会引发 InvalidCastException
。
我似乎找不到任何关于如何允许用户 select 图表然后在 VSTO 加载项中修改 selected 图表的文档。
您的代码需要确定 Selection 是否实际包含 Chart 对象,然后从中派生 Chart。为了确定一个 Selection 包含什么,在使用 VB.NET 时使用 TypeName 方法,其中 returns 一个 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