trying to add a button on a activesheet programmatically

Joined
Feb 8, 2006
Messages
1
Reaction score
0
Hi,
I'm trying to add a button on an active sheet programmatically, which will some code in the code module. But I have runtime error '9': subscript out of range.
Here is the code: (the problem is probably with the bold statement)

Sub AddSheetButton()
'On Error Resume Next
Application.ScreenUpdating = False
Dim s As Shape
Dim NewButton As OLEObject
Set NewButton = ActiveSheet.OLEObjects.Add _
("Forms.CommandButton.1")
With NewButton
.Left = 4
.Top = 4
.Width = 60
.Height = 24
.Object.Caption = "RunQuery"
End With

c = 0
For Each s In ActiveSheet.Shapes
If InStr(s.Name, "CommandButton") Then
c = c + 1
End If
Next
code = ""
code = code & "Private Sub CommandButton" & c & "_Click" & vbCr
code = code & "Msgbox ""This is CommandButton" & c & """" & vbCr
code = code & "End Sub"

With ActiveWorkbook.VBProject. _
VBComponents(ActiveSheet.Name).CodeModule
NextLine = .CountOfLines + 1
.InsertLines NextLine, code
End With
Application.ScreenUpdating = True
On Error GoTo 0
End Sub

When using the code in a fresh workbook with no buttons on the any sheet, the code works fine; but the book I am using has about 60 sheets and almost each sheet has at least 6-7 buttons.

Thanks in advance.

John Zhang
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top