如何获得CommandButton集合?

时间:2017-02-09 11:43:07

标签: excel vba excel-vba

我需要在工作表上列出大量旧ActiveX命令按钮的标题。

我如何参考该系列?

伪代码:

For each btn in Activesheet.CommandButtons 
     Debug.Print btn.Caption
Next btn

3 个答案:

答案 0 :(得分:5)

Dim s As Worksheet

Set s = ActiveSheet

Dim o As OLEObject

For Each o In s.OLEObjects

    If TypeName(o.Object) = "CommandButton" Then
        Debug.Print o.Object.Caption
    End If

Next

答案 1 :(得分:2)

更新了我在MrExcel网站上找到的代码:

Dim BtnActX As Integer
Dim MyShapes As OLEObjects
Dim Btn As OLEObject

'OLE Programmatic Identifiers for Commandbuttons = Forms.CommandButton.1
Set MyShapes = ActiveSheet.OLEObjects
For Each Btn In MyShapes
If Btn.progID = "Forms.CommandButton.1" Then
BtnActX = BtnActX + 1
abc = Btn.Object.Caption
MsgBox "command button text is: " & abc
End If
Next

答案 2 :(得分:1)

如何循环浏览工作表中的OLEObjects,您可以使用他们的progID并将其视为等于" Forms.CommandButton.1"。

注意:请不要使用ActiveSheet,而应使用完全限定的对象,例如Worksheets("Sheet1")

Option Explicit

Sub FindCommandButtonsInOLEObjects()

Dim Sht                 As Worksheet
Dim Obj                 As OLEObject

Set Sht = ThisWorkbook.Sheets("Sheet1") '<-- modify "Sheet1" to your sheet's name

' loop thourgh all OLE objects in "Sheet1"
For Each Obj In Sht.OLEObjects
    If Obj.progID Like "Forms.CommandButton.1" Then ' <-- check if current object is type Comman Button
        Debug.Print Obj.Object.Caption
    End If
Next Obj 

End Sub