making and coding a commandbutton

CMBond

New Member
Joined
Jul 13, 2007
Messages
15
I am trying to create a formula to first create a new page, and then add a button with code to that page, using only Visual Basic code. When I run the macro, I get the error 9, subscript out of range. Any explanations?

Code:
Sub CreateGraphPg()

Numsheets = ActiveWorkbook.Sheets.Count

Dim NewSheet As Worksheet
Dim NewButton As OLEObject
Dim wBook As Workbook
Dim Code As String

Set wBook = ActiveWorkbook
Set NewSheet = Sheets.Add
NewSheet.Move After:=Sheets(Numsheets + 1)
NewSheet.Name = "Graphs"
Set NewButton = NewSheet.OLEObjects.Add("Forms.CommandButton.1")
With NewButton
    .Left = 280
    .Top = 15
    .Width = 100
    .Height = 25
    .Object.Caption = "Graph"
End With

Code = "Private Sub CommandButton1_Click()" & vbCrLf
Code = Code & "   MakeGraph" & vbCrLf
Code = Code & "End Sub"

With wBook.VBProject.VBComponents(NewSheet.Name).CodeModule
    Nextline = .CountOfLines + 1
    .InsertLines Nextline, Code
End With

End Sub

EDIT: added code tags - Smitty
 

Excel Facts

Square and cube roots
The =SQRT(25) is a square root. For a cube root, use =125^(1/3). For a fourth root, use =625^(1/4).

VoG

Legend
Joined
Jun 19, 2002
Messages
63,650
Code:
NewSheet.Move After:=Sheets(Numsheets + 1)

should be

Code:
NewSheet.Move After:=Sheets(Numsheets)
 

CMBond

New Member
Joined
Jul 13, 2007
Messages
15
the line that the error occurs on is

With wBook.VBProject.VBComponents(NewSheet.Name).CodeModule
 
Master Excel Bundle

Excel contains over 450 functions, with more added every year. That’s a huge number, so where should you start? Right here with this bundle.

Forum statistics

Threads
1,164,148
Messages
5,835,680
Members
430,375
Latest member
datdog22

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top