代码之家  ›  专栏  ›  技术社区  ›  gizgok

如何在excel中创建动态按钮

  •  3
  • gizgok  · 技术社区  · 14 年前

    1 回复  |  直到 6 年前
        1
  •  8
  •   MikeD    14 年前

    我假设在查询填满表后,您将遍历记录,搜索条件并“执行操作”。因此,我认为要放置按钮的位置由ActiveSheet()中的Range()对象表示

    Sub CreateDynamicButton()
    Dim MyR As Range, MyB As OLEObject
    Dim MyR_T As Long, MyR_L As Long
    
    
        Set MyR = Range("C110") 'just an example - you get that from your own script
        MyR_T = MyR.Top         'capture positions
        MyR_L = MyR.Left        '...
        'create button
        Set MyB = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False, DisplayAsIcon:=False)
    
        'set main button properties
        With MyB
            .Name = "MyPrecodedButton"     'important - code must exist ... see below
            .Object.Caption = "MyCaption"
            .Top = MyR_T
            .Left = MyR_L
            .Width = 50
            .Height = 18
            .Placement = xlMoveAndSize
            .PrintObject = True            'or false as per your taste
        End With
    
    End Sub
    

    如果事先在活动工作表中创建了以下例程

    Private Sub MyPrecodedButton_Click()
        MsgBox "Co-Cooo!"
    End Sub
    

    当你按下上面创建的按钮(在XP/SP2+excel2003下测试)时,一个漂亮的消息框就会出现。

    .Name = "..." 将自动失败,并开始命名按钮“CommandButton1”及以上。

    我不得不承认,这听起来有点不寻常,我可能不喜欢安装动态按钮的预编码子的行动,相反,我会做一个初始对话框之前,查询通过复选框,如“截断后X行(Y/N)”和类似的选项-但你会有很好的理由这样做你的方式。

    希望有帮助-祝你好运