Thursday, January 22, 2009

Excel Using VBA to write VBA code (create multiple buttons)

Excel Using VBA to write VBA code (create multiple buttons): "Sub AddComm_button()

Dim code As String
Dim j As Integer

Sheets('Sheet1').Select


For j = 1 To 2
'add button
ActiveSheet.OLEObjects.Add ClassType:='Forms.CommandButton.1', _
Left:=126 * j, Top:=96, Width:=126.75, Height:=25.5

'Code for button
code = ''
code = 'Sub CommandButton' & Trim(Str(j)) & '_Click()' & vbCrLf
code = code & ' Sheets(''Sheet' & Trim(Str(j)) & ''').Activate' & vbCrLf
code = code & 'End Sub'

'Write code for button
With ThisWorkbook.VBProject.VBComponents('Sheet1').CodeModule
.InsertLines .CountOfLines + 1, code
End With
Next j
End Sub"

No comments: