如何将代码分配给动态创建的按钮?

时间:2015-07-13 09:43:16

标签: excel vba class excel-vba excel-2010

首先:我是VBA的初学者,我不知道UserForms的工作原理。

那说我正在尝试将代码分配给3个动态创建的CommandButtons。

经过一些研究this页后,我刚写了一个代码来编写按钮的代码。问题是,我需要分发这个工作簿,所以这种方法不再好了。

我经常了解1234)并发现this帖子。我试图做@SiddharthRout做的例子,但我没有成功。我试图理解ClassModule是如何工作的,但我不能(12)。我认为一个代码正好是@SiddharthRout可以解决我的问题,但我无法使其在普通模块上运行。

长话短说:我需要一个代码来将代码分配给CommandButtons而不使用可扩展性(代码编写代码)。

修改
我想在普通工作表上创建这些按钮,而不是在UserForm上创建。

2 个答案:

答案 0 :(得分:0)

阅读本文: http://scriptorium.serve-it.nl/view.php?sid=13

Sub MakeForm()
    Dim TempForm As Object ' VBComponent
    Dim FormName As String
    Dim NewButton As MSForms.CommandButton
    Dim TextLocation As Integer
    ' ** Additional variable
    Dim X As Integer

    'Locks Excel spreadsheet and speeds up form processing
    Application.VBE.MainWindow.Visible = False
    Application.ScreenUpdating = False
    ' Create the UserForm
    Set TempForm = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm)
    'Set Properties for TempForm
    With TempForm
    .Properties("Caption") = "Temporary Form"
    .Properties("Width") = 200
    .Properties("Height") = 100
    End With
    FormName = TempForm.Name

    ' Add a CommandButton
    Set NewButton = TempForm.Designer.Controls _
    .Add("forms.CommandButton.1")
    With NewButton
    .Caption = "Click Me"
    .Left = 60
    .Top = 40
    End With
    ' Add an event-hander sub for the CommandButton
    With TempForm.CodeModule

    ' ** Add/change next 5 lines
    ' This code adds the commands/event handlers to the form
    X = .CountOfLines
    .InsertLines X + 1, "Sub CommandButton1_Click()"
    .InsertLines X + 2, "MsgBox ""Hello!"""
    .InsertLines X + 3, "Unload Me"
    .InsertLines X + 4, "End Sub"
    End With

    ' Show the form
    VBA.UserForms.Add(FormName).Show
    '
    ' Delete the form
    ThisWorkbook.VBProject.VBComponents.Remove VBComponent:=TempForm
  End Sub 

答案 1 :(得分:0)

This code from here:

Sub CreateButtons()
  Dim arrNames            As Variant
  Dim arrCaptions         As Variant
  Dim Wkb                 As Workbook
  Dim Wks                 As Worksheet
  Dim NewBtn              As OLEObject
  Dim Code                As String
  Dim NextLine            As Long
  Dim LeftPos             As Long
  Dim Gap                 As Long
  Dim i                   As Long

  'The Workbook, where...
  Set Wkb = ActiveWorkbook
  '... the worksheet is, where the button will be created
  ' and code will be written.
  Set Wks = Wkb.Worksheets(1)

  'Commandbuttons' CODENAMES in array
  arrNames = Array("cmbName1", "cmbName2", "cmbName3")
  'Commandbuttons' captions in array
  arrCaptions = Array("First Task", "Second Task", "Third Task")

  'Button pos.
  LeftPos = 100

  Gap = 15

  For i = LBound(arrNames) To UBound(arrNames)

    'Add a CommandButton to worksheet
    Set NewBtn = Wks.OLEObjects.Add(ClassType:="Forms.CommandButton.1")

    'Set button's properties
    With NewBtn
        .Left = LeftPos
        .Top = 5
        .Width = 65
        .Height = 30
        .Name = arrNames(i)
        .Object.Caption = arrCaptions(i)
        .Object.Font.Size = 10
        .Object.Font.Bold = True
        .Object.Font.Name = "Times New Roman"
    End With

    'Add the event handler code
    Code = "Sub " & NewBtn.Name & "_Click()" & vbCrLf
    Code = Code & "     MsgBox ""Hello...""" & vbCrLf
    Code = Code & "End Sub"

    '"Code" is a string
    With Wkb.VBProject.VBComponents(Wks.CodeName).CodeModule
        'Find last line in Codemodule
        NextLine = .CountOfLines + 1
        .InsertLines NextLine, Code
    End With

    'NEXT button's pos.
    LeftPos = LeftPos + NewBtn.Width + Gap

  Next i

End Sub