End sub creates "Runtime Error 91: Object variable or with block variable not set"

SeanWise

New Member
Joined
Dec 2, 2016
Messages
17
Apparently this happens when a variable is not defined, but all mine are, as far as I can tell.

Also, when debugging, the error appears on the End Sub line. That is, the macro (seems to) exit correctly, but as it exits I get the error msg. If the error box could be forced to not appear it would be ok lol. (joking)

Any hints or solutions would be greatly appreciated.


To make explanations simpler:

Psuedocode

Inputbox takes user input
If user input invalid, call Close Subroutine
Else run macro (runs correctly)
.
.
.
V
Close Sub()
Select "menu" worksheet
Unload Me 'exit macro.
End Sub <-----error while debugging happens here.



The actual Code:


Code:
Option Explicit
Public ProdSht As String
'This code creates a new worksheet, for a new Product
Public Sub UserForm_Initialize()


Dim sheetName As String
Dim ws As Worksheet, WshSrc As Worksheet, WshTrg As Worksheet
Dim InputDemand As Integer, StartPeriod As Integer, StartYear As Integer
Dim i As Long, A As Long


'open inputbox for user to type Productline code. This will also be the name of the worksheet
    ProdSht = InputBox(Prompt:="Enter New Product Code:", Title:="Create New Product Sheet", Default:="I.e. A1")
        On Error GoTo 0
        If ProdSht = "I.e. A1" Or ProdSht = vbNullString Then       'ensure Programs worksheet is selected.
            MsgBox "Invalid Name."
[B]            Call CmdDone_Click   <-----Call the problem sub from here.[/B]
            Exit Sub
        End If
        
            Set ws = Sheets.Add(After:=Sheets(Worksheets.Count))         'create sheet
            ws.Name = ProdSht
        
        
 'Populate with formatting and headings from the Template sheet.


Set WshSrc = ThisWorkbook.Worksheets("Template")
Set WshTrg = ThisWorkbook.Worksheets(ProdSht)


    WshSrc.Cells.Copy
    With WshTrg.Cells
        .PasteSpecial Paste:=xlPasteColumnWidths
        .PasteSpecial Paste:=xlPasteFormats
        .PasteSpecial Paste:=xlPasteFormulasAndNumberFormats
        Application.CutCopyMode = False
    End With
    
Sheets("Template").UsedRange.Copy
Sheets(ProdSht).Cells.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone
  '-----------------------------------------------------------
        'Create Years and Quarters


StartYear = InputBox(Prompt:="In what year does your data start?", _
          Title:="Enter Year", Default:="I.e. 2012")                                'Ask for the year you you wish to start recording data from.




Set ws = ActiveSheet


A = 9                                                                'this is where the first year is placed
For i = 0 To 100                                                     'place 100 years on the sheet starting from the first year...
    Cells(A, 1).Value = StartYear
    A = A + 4                                                        'space them out every 4 lines
    StartYear = StartYear + 1
Next i


'Create quarterly periods
A = 7
    For i = 0 To 400
        A = A + 1
        Cells(A, 2).Value = StartPeriod
        StartPeriod = StartPeriod + 1
        If StartPeriod = 5 Then
            StartPeriod = 1
        End If
    Next i


End Sub




Public Sub CmDNext_Click()
Dim i As Integer
Dim AddData As Variant
Dim sht As Worksheet
Dim Ans As String
Dim Y As Double, YRow As Double


Set sht = ThisWorkbook.Worksheets(ProdSht)


    If Trim(TextBoxAddYear.Value & vbNullString) = vbNullString Then 'if user clicks next but forgets to add a tear, remind them.
        MsgBox "No Year detected"
        Exit Sub
    Else
        For i = 1 To 4
        AddData = 0
            If Not Trim(("TextBoxAddQtr" & i) & vbNullString) = vbNullString Then                   'for each qtr
                AddData = AddDataForm.Controls("TextBoxAddQtr" & i)
                YRow = TextBoxAddYear.Value + (i / 10)
                On Error Resume Next
                Y = Application.WorksheetFunction.Match(YRow, ActiveSheet.Range("C1:C1000"), 0)     'find year and qtr to add data to
                    If Y = 0 Then                                                                  'if can't find it
                       MsgBox "Couldn't find that year."                                            'tell user if they have made an error
                       Exit Sub                                                                     'return to the data entry form
                    End If
                On Error GoTo 0
                    If Cells(Y, 4) > 0 Then                                                         'does cell already have data?
                        Ans = MsgBox("Cell has data. Overwrite?", vbQuestion + vbYesNo)             'does user want to overwrite
                            If Ans = vbYes Then                                                     'if yes, do so
                                Cells(Y, 4) = AddData
                            ElseIf Ans = vbNo Then                                                  'if not
                                Exit Sub                                                            'return to the data entry form
                            End If
                    End If
                Cells(Y, 4) = AddData                                                               'if none of the above issues arise, just add data.
            End If
        Next i                                                                                      'repeat for each qtr
    End If
    
    MsgBox "New Data Added"                                                                         'notify user data has been added
    TextBoxAddYear.Value = ""                                                                       'clear all textboxes for next data entry.
    TextBoxAddQtr1.Value = ""
    TextBoxAddQtr2.Value = ""
    TextBoxAddQtr3.Value = ""
    TextBoxAddQtr4.Value = ""
    
End Sub


Private Sub CmdClear_Click()                'Clears all textboxes.
    TextBoxAddYear.Value = ""
    TextBoxAddQtr1.Value = ""
    TextBoxAddQtr2.Value = ""
    TextBoxAddQtr3.Value = ""
    TextBoxAddQtr4.Value = ""
End Sub


Private Sub CmdDone_Click()


ThisWorkbook.Sheets("Program").Select                   'ensure Programs worksheet is selected.
Unload Me                                               'exit macro.
End Sub                                  [B]<----- Error happens here[/B]
 

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
SeanWise,

Not sure why you have included 'Unload me' ??? Try deleting it.

Hope that helps.
 
Upvote 0
Hi Snake

Good Question. This code is run from a userform. Private Sub CmdDone_Click is called when I want to close the form and Unload me does that.
 
Upvote 0
I looks like you are calling a command button click event code which would normally run when button clicked?

The main issue I reckon is that all this is within the Initialise event code for the form. So as and when you have 'Unload Me' you are trying to unload a form that has not yet initialised and displayed , at which point 'Me' is not defined, hence the error.
 
Upvote 0
Ok, I changed the code so that the Initialize subroutine is different from the rest of the code, but still get the error.


Code:
Public InputDemand As Integer, StartPeriod As Integer
Public StartYear As String
Public i As Long, A As Long
'This code creates a new worksheet, for a new Product


Public Sub UserForm_Initialize()
Call GetData
End Sub


Public Sub GetData()
'open inputbox for user to type Productline code. This will also be the name of the worksheet
    ProdSht = InputBox(Prompt:="Enter New Product Code:", Title:="Create New Product Sheet", Default:="I.e. A1")
       
        For Each ws In Worksheets                                   'check its not duplicate
                If ws.Name = ProdSht Then                           'if it is, exit to menu
                    MsgBox "Product Already Exists"
                    Call CmdDone_Click
                    Exit Sub
                End If
        Next ws
            
        If ProdSht = "I.e. A1" Or ProdSht = vbNullString Then       'ensure Programs worksheet is selected.
            MsgBox "Invalid Name."                                  'otherwise return to menu
            Call CmdDone_Click
            Exit Sub
        Else
            Call Create
        End If
        
 End Sub
        
        
Public Sub Create()
 'Populate with formatting and headings from the Template sheet.


Set ws = Sheets.Add(After:=Sheets(Worksheets.Count))         'create sheet
            ws.Name = ProdSht
            
Set WshSrc = ThisWorkbook.Worksheets("Template")
Set WshTrg = ThisWorkbook.Worksheets(ProdSht)


    WshSrc.Cells.Copy
    With WshTrg.Cells
        .PasteSpecial Paste:=xlPasteColumnWidths
        .PasteSpecial Paste:=xlPasteFormats
        .PasteSpecial Paste:=xlPasteFormulasAndNumberFormats
        Application.CutCopyMode = False
    End With
    
Sheets("Template").UsedRange.Copy
Sheets(ProdSht).Cells.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone
Call Yrs
End Sub
  '-----------------------------------------------------------
Public Sub Yrs()
        'Create Years and Quarters


StartYear = InputBox(Prompt:="In what year does your data start?", _
          Title:="Enter Year", Default:="I.e. 2012")                                'Ask for the year you you wish to start recording data from.
        If StartYear = "I.e. 2012" Or StartYear = vbNullString Then       'ensure year is valid.
            MsgBox "Invalid Year."                                          'otherwise return to menu
            Call Delete
            Exit Sub
        ElseIf Not IsNumeric(StartYear) Then
            MsgBox "Wrong Format"                                        'otherwise return to menu
            Call Delete
            Exit Sub
        ElseIf Not (Len(StartYear) = 4) Then
         MsgBox "Year too long/short."                                        'otherwise return to menu
            Call Delete
            Exit Sub
        End If


Set ws = ActiveSheet


A = 9                                                                'this is where the first year is placed
For i = 0 To 100                                                     'place 100 years on the sheet starting from the first year...
    Cells(A, 1).Value = StartYear
    A = A + 4                                                        'space them out every 4 lines
    StartYear = StartYear + 1
Next i


'Create quarterly periods
A = 7
    For i = 0 To 400
        A = A + 1
        Cells(A, 2).Value = StartPeriod
        StartPeriod = StartPeriod + 1
        If StartPeriod = 5 Then
            StartPeriod = 1
        End If
    Next i


End Sub




Public Sub CmDNext_Click()
Dim i As Integer
Dim AddData As Variant
Dim sht As Worksheet
Dim Ans As String
Dim Y As Double, YRow As Double


Set sht = ThisWorkbook.Worksheets(ProdSht)


    If Trim(TextBoxAddYear.Value & vbNullString) = vbNullString Then 'if user clicks next but forgets to add a tear, remind them.
        MsgBox "No Year detected"
        Exit Sub
    Else
        For i = 1 To 4
        AddData = 0
            If Not Trim(("TextBoxAddQtr" & i) & vbNullString) = vbNullString Then                   'for each qtr
                AddData = AddDataForm.Controls("TextBoxAddQtr" & i)
                YRow = TextBoxAddYear.Value + (i / 10)
                Y = Application.WorksheetFunction.Match(YRow, ActiveSheet.Range("C1:C1000"), 0)     'find year and qtr to add data to
                    If Y = 0 Then                                                                  'if can't find it
                       MsgBox "Couldn't find that year."                                            'tell user if they have made an error
                       Exit Sub                                                                     'return to the data entry form
                    End If
                    If Cells(Y, 4) > 0 Then                                                         'does cell already have data?
                        Ans = MsgBox("Cell has data. Overwrite?", vbQuestion + vbYesNo)             'does user want to overwrite
                            If Ans = vbYes Then                                                     'if yes, do so
                                Cells(Y, 4) = AddData
                            ElseIf Ans = vbNo Then                                                  'if not
                                Exit Sub                                                            'return to the data entry form
                            End If
                    End If
                Cells(Y, 4) = AddData                                                               'if none of the above issues arise, just add data.
            End If
        Next i                                                                                      'repeat for each qtr
    End If
    
    MsgBox "New Data Added"                                                                         'notify user data has been added
    TextBoxAddYear.Value = ""                                                                       'clear all textboxes for next data entry.
    TextBoxAddQtr1.Value = ""
    TextBoxAddQtr2.Value = ""
    TextBoxAddQtr3.Value = ""
    TextBoxAddQtr4.Value = ""
    
End Sub


Private Sub CmdClear_Click()                'Clears all textboxes.
    TextBoxAddYear.Value = ""
    TextBoxAddQtr1.Value = ""
    TextBoxAddQtr2.Value = ""
    TextBoxAddQtr3.Value = ""
    TextBoxAddQtr4.Value = ""
End Sub


Private Sub CmdDone_Click()


ThisWorkbook.Sheets("Menu").Select                   'ensure Programs worksheet is selected.
Unload Me                                               'exit macro.
End Sub


Sub Delete()


Application.DisplayAlerts = False


Worksheets(ProdSht).Delete


Application.DisplayAlerts = True
Call CmdDone_Click
End Sub
 
Upvote 0
Ok, was looking at it upside down.

Created a new "ending" subroutine not linked to the Unload me and it works.

Just like what you said, i was trying to close a userform that hadn;t opened yet.

Cheers Snake!
 
Upvote 0

Forum statistics

Threads
1,214,908
Messages
6,122,187
Members
449,071
Latest member
cdnMech

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