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
 

Some videos you may like

Excel Facts

Highlight Duplicates
Home, Conditional Formatting, Highlight Cells, Duplicate records, OK to add pink formatting to any duplicates in selected range.

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
 

Watch MrExcel Video

Forum statistics

Threads
1,122,519
Messages
5,596,634
Members
414,082
Latest member
sasmita

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