参考运行时在Excel中使用VBA添加的命令button

在运行期间,用户可以将任意数量的ActiveX命令button添加到工作表1.我需要用VBA引用这些新button,但不知道如何。

我知道button名称会显示的逻辑进程:例如。

(节点#X2)-2 =命令button#=我

我需要以某种方式引用这些新创build的button,我正在思考的是:

Sheet1.Controls("CommandButton" & i).Select 

如果有人知道正确的语法或替代方法,请告知!

UPDATE

 Public Sub Node_Button_Duplication() ' 'Comments: Copies and pastes Node 1's button to the appropriate column ' Copy Node 1 button and paste in appropriate location ActiveSheet.Shapes("CommandButton1").Select Selection.Copy Cells(5, 10 + 7 * (NumNodes - 1) - 1).Select ActiveSheet.Paste Selection.ShapeRange.IncrementLeft 47.25 Selection.ShapeRange.IncrementTop -13.5 End Sub 

跟进

 Public Sub Node_Button_Duication() ' 'Comments: Copies and pastes Node 1's button to the appropriate column Dim shp As Shape ' Copy Node 1 button and paste in appropriate location ActiveSheet.Shapes("CommandButton1").Select Selection.Copy Cells(5, 10 + 7 * (NumNodes - 1) - 1).Select ActiveSheet.Paste Selection.ShapeRange.IncrementLeft 47.25 Selection.ShapeRange.IncrementTop -13.5 Debug.Print Selection.Name Set shp = ActiveSheet.Shapes(Selection.Name) With shp.OLEFormat.Object.Object .Caption = "Test" .Left = 15 .Top = 15 End With End Sub 

这给我一个运行时错误“438:对象不支持这个属性或方法,我不是特别明白

 shp.OLEFormat.Object.Object 

 Public Sub Node_Button_Duplication() ActiveSheet.Shapes("CommandButton1").Select Selection.Copy Cells(5, 10 + 7 * (NumNodes - 1) - 1).Select ActiveSheet.Paste Selection.ShapeRange.IncrementLeft 47.25 Selection.ShapeRange.IncrementTop -13.5 '~~> This will give you the name Debug.Print Selection.Name End Sub 

跟进

如果你知道命令button的名字,那么你可以改变像这样的属性。

 Option Explicit Sub Sample() Dim shp As Shape '~~> Since you already have the name replace "CommandButton1" by '~~> the name that you have Set shp = ActiveSheet.Shapes("CommandButton1") With shp.OLEFormat.Object .Object.Caption = "Test" .Left = 15 .Top = 15 End With End Sub 

你也可以像这样结合上面两个

 Public Sub Node_Button_Duplication() Dim shp As Shape ActiveSheet.Shapes("CommandButton1").Select Selection.Copy Cells(5, 10 + 7 * (NumNodes - 1) - 1).Select ActiveSheet.Paste Selection.ShapeRange.IncrementLeft 47.25 Selection.ShapeRange.IncrementTop -13.5 '~~> This will give you the name Debug.Print Selection.Name Set shp = ActiveSheet.Shapes(Selection.Name) With shp.OLEFormat.Object .Object.Caption = "Test" .Left = 15 .Top = 15 End With End Sub 

如果你需要遍历所有的button,然后使用这个代码。

 Sub CommanButtons() Dim wks As Worksheet Dim OLEObj As OLEObject '~~> set it as per the relevant sheet Set wks = Worksheets("sheet1") For Each OLEObj In wks.OLEObjects If TypeOf OLEObj.Object Is MSForms.CommandButton Then Debug.Print OLEObj.Object.Caption End If Next OLEObj End Sub