Adding SINGLE button

  • Adding Single Button
  •  

    Code:

     

    Private Sub CommandButton1_Click()
    'If we want to repeat the process first remove existing Buttons
    ActiveSheet.Buttons.Delete
    'Define Button
    Dim b As Button
    'Define Measures Button
    l = 200
    t = 100
    w = 100
    h = 55
    'Adding button to variable
    Set b = Buttons.Add(l, t, w, h)
    'Set b = Buttons.Add(Left:=200, Top:=100, Width:=100, Height:=55)
    'Caption to Button
    b.Caption = "i m button"
    MsgBox "Button Created"
    End Sub

    Download The Workbook

     

    Creation of Multiple Buttons through Loop

     

    Code:

     

    Private Sub CommandButton1_Click()
    ActiveSheet.Buttons.Delete
    Dim b As Button
    l = 300 ' left
    t = 100 'top
    w = 100 'Width
    h = 55 'Height
    'We need to add 5 buttons
    For i = 1 To 5
    Set b = Buttons.Add(l, t, w, h)
    'Set b = Buttons.Add(Left:=300, Top:=100, Width:=100, Height:=55)
    b.Caption = "Button" & i
    MsgBox "Button " & i & " has been Created"
    'For each iteration increase the TOP value by 100
    t = t + 100
    Next
    End Sub

    Download The Workbook

     

    Creation & Adjust buttons in cells through Loop

     

     

    Code:

     

    Private Sub CommandButton1_Click()
    'Delete existing buttons
    ActiveSheet.Buttons.Delete
    'Increase the colums width for max size of command button
    Columns("g").ColumnWidth = 25
    Application.ScreenUpdating = False
    Dim b As Button
    n = 3
    Dim r As Range
    'i need 5 buttons
    For i = 1 To 5
    Set r = Range("G" & n)
    'cell size is the measure to a button
    Set b = ActiveSheet.Buttons.Add(r.Left, r.Top, r.Width, r.Height)
    b.Caption = "button" & i
    MsgBox "button " & i & " has been created"
    'Increase the row number by 2 for each iteration of loop
    n = n + 2
    Next
    Application.ScreenUpdating = True
    End Sub

    Download The workbook