创建新工作表时创建命令按钮vba

时间:2015-02-12 06:45:48

标签: excel vba excel-vba

我正在尝试在创建新工作表时创建命令按钮。但是我遇到了错误。错误438,对象不支持此属性或方法。这里需要一些帮助。干杯。

Sub wdlsinflow()

    Dim r As Range, LstRw As Long, LstCo As Long
    Dim Obj As Object
    Dim Code As String

    LstRw = Sheets("sheet2").Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row
    LstCo = Sheets("sheet2").Cells.Find(What:="*", SearchOrder:=xlColumns, SearchDirection:=xlPrevious, LookIn:=xlValues).Column

    Const myCompany As String = "RECEIVABLES - INFLOWS"
    Set r = Sheets("sheet2").Columns(1).Find(myCompany, , , 1)

    If Not r Is Nothing Then
        If Not IsSheetExists(myCompany) Then
            Sheets.Add(After:=Sheets(Sheets.Count)).Name = myCompany
        End If

        With Sheets(myCompany)
            .Cells.Clear
            Range(r, Sheets("sheet2").Cells(LstRw, LstCo)).Copy .Cells(1)

         Set Obj = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
          Link:=False, DisplayAsIcon:=False, Left:=200, Top:=100, Width:=100, Height:=35)
             Obj.Name = "TestButton"
            'buttonn text
             ActiveSheet.OLEObjects(1).Object.Caption = "Test Button"



             Code = "Sub ButtonTest_Click()" & vbCrLf
             Code = Code & "Call Tester" & vbCrLf
             Code = Code & "End Sub"
        End With
    End If

     With Sheets(myCompany).VBProject.VBComponents(Sheets(myCompany).Name).CodeModule
        .insertlines .CountOfLines + 1, Code
    End With

End Sub

1 个答案:

答案 0 :(得分:0)

这对我有用:

Sub wdlsinflow()

    Dim sht As Worksheet
    Dim Obj As Object
    Dim Code As String
    Dim cmod

    Set sht = Sheets.Add(After:=Sheets(Sheets.Count))

    With sht
        .Name = "blah"
        .Cells.Clear


        Set Obj = .OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
                               Link:=False, DisplayAsIcon:=False, Left:=200, _
                               Top:=100, Width:=100, Height:=35)

        Obj.Name = "ButtonTest" '<< name must match code below...
        Obj.Object.Caption = "Test Button"

        Code = "Sub ButtonTest_Click()" & vbCrLf & _
                "   Call Tester" & vbCrLf & _
                "End Sub"

        With .Parent.VBProject.VBComponents(.CodeName).CodeModule
            .insertlines .CountOfLines + 1, Code
        End With
    End With

End Sub