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

Bring active cell back into view
Start at A1 and select to A9999 while writing a formula, you can't see A1 anymore. Press Ctrl+Backspace to bring active cell into view.
Code:
NewSheet.Move After:=Sheets(Numsheets + 1)

should be

Code:
NewSheet.Move After:=Sheets(Numsheets)
 
Upvote 0
the line that the error occurs on is

With wBook.VBProject.VBComponents(NewSheet.Name).CodeModule
 
Upvote 0

Forum statistics

Threads
1,214,631
Messages
6,120,640
Members
448,974
Latest member
DumbFinanceBro

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
Back
Top