问题
I would like to check which objects are selected/active.
In PowerPoint and Word it is quite easy, but in Excel... nothing what I checked is working. Globals.ThisAddin.ActiveWindow.Selection is of type: dynamic. I added reference to VisualBasic, to have an access to TypeName function.
If chart is selected it returns type "ChartObject"... so I am setting it to variable of ChartObject type, but then I have no access to almost any of its properties and methods, for example when I try to read name that object or trying to return chart from it gives me an error.
When there is few shapes selected then TypeName function returns me type: "DrawingObjects"... but I am not able to read anything from it. I was trying to get get from it ShapeRange, but again... errors.
Could you advise me how to get all selected objects?
回答1:
I managed to create code that works (for charts):
public static List<XL.Chart> ReturnSelectedCharts(dynamic selection )
{
List<XL.Chart> charts=new List<XL.Chart>();
XL.ShapeRange selectedShapeRange = null;
XL.Chart chart=null;
try
{
selectedShapeRange = Globals.ThisAddIn.Application.Selection.ShapeRange;
for (int i = 1; i <= selectedShapeRange.Count; i++)
{
XL.Shape shape=selectedShapeRange.Item(i);
if (shape.HasChart==MsoTriState.msoTrue)
{
chart = shape.Chart;
charts.Add(chart);
}
}
}
catch
{
}
if (charts.Count==0)
{
try
{
chart = Globals.ThisAddIn.Application.ActiveChart;
charts.Add(chart);
}
catch (Exception)
{
}
}
return charts;
}
回答2:
In Excel VBA TypeName() can return any of a large variety of names corresponding to a variety of Shapes.
Once we have determined that the Name (as defined by TypeName()) corresponds to a specific Shape-type, we can use the Name
of Selection
to define that specific Shape:
Sub WhatIsSelected()
Dim sh As Shape
If TypeName(Selection) = "Rectangle" Then
Set sh = ActiveSheet.Shapes(Selection.Name)
End If
MsgBox TypeName(Selection) & vbCrLf & sh.Name
End Sub
Now that sh
has been both Dimmed
and Set
we can get all it Properties and use all its Methods.
来源:https://stackoverflow.com/questions/36221728/how-to-check-which-shapes-objects-are-selected-active