excelperfect 在有些VBA代码解决方案中,需要先确定所选择的对象,这样才能使用合适的代码来对其进行相应的操作。本文介绍的代码可用来确定所选对象。 判断是否选择单元格或单元格区域 下面的代码展示了如何确保是对单元格或单元格区域执行操作: Sub DoWithRange() Dim rng As Range '确保选择了单元格区域 If TypeName(Selection) <>'Range' Then MsgBox '请选择单元格区域!' Exit Sub Else Set rng = Selection '操作代码 End If End Sub 判断是否选择图表 下面的代码展示了如何确保是对图表执行操作: Sub DoWithChart() Dim cht As Chart '是否选择了图表 If ActiveChart Is Nothing Then MsgBox '请选择图表!' Exit Sub Else Set cht = ActiveChart '操作代码 End If End Sub 判断是否选择图表系列 下面的代码展示了如何确保选择了图表系列: Sub DoWithChartSeries() Dim srs As Series '是否选择了图表系列 If TypeName(Selection) = 'Series'Then Set srs = Selection '操作代码 Else MsgBox '请选择图表系列!' Exit Sub End If End Sub 判断是否选择表 下面的代码展示了如何确保所选单元格处于表中: Sub DoWithTable() Dim tbl As ListObject On Error Resume Next Set tbl = ActiveCell.ListObject On Error GoTo 0 If tbl Is Nothing Then MsgBox '请选择表中的单元格!' Exit Sub End If '操作代码 End Sub 判断是否选择形状 下面的代码展示了如何确保在执行操作前用户选择了形状: Sub DoWithShape() Dim shp As Shape On Error Resume Next Set shp =ActiveSheet.Shapes(Selection.Name) On Error GoTo 0 If shp Is Nothing Then MsgBox '请选择形状!' Exit Sub End If '操作代码 End Sub 上面展示了用来确定一些主要对象的代码,在确定是我们要操作的对象后,再执行相应的代码对该对象进行想要的操作,确保达到我们的目的。
|
|
来自: hercules028 > 《VBA》