Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA restarting same Subroutine within itself based on VbMsgBoxResult

I'm trying to get my Sub to restart based on MsgBoxReults. The code I have doesn't contain any errors, but won't restart based on the users choice (hopefully, having an IF statement within another IF isn't the issue)

Please assist.

Sub ContinueWeatherList()

Dim Weather As String
'Assigning a Message Box result as a Variable for Yes/No
Dim MoreWeather As VbMsgBoxResult

Weather = InputBox("Type in the weather for " & Range("C1").End(xlDown) + 1)

If Weather = "" Then
    MsgBox ("No data entered. Your response has not been recorded"), vbExclamation
Else
    Range("C1").End(xlDown).Offset(1, 0).Value = Range("C1").End(xlDown) + 1
    Range("A1").End(xlDown).Offset(1, 0).Value = Range("A1").End(xlDown) + 1
    Range("B1").End(xlDown).Offset(1, 0).Value = Weather
    Columns("A:C").EntireColumn.AutoFit
    MsgBox "Thank you for entering your data " & vbNewLine & "Would you like to enter another?", vbYesNo

    'Using IF statement to decide what happens for each condition
    If MoreWeather = vbYes Then
        ''Call' command won't reinitiate Sub / *NEED TO FIX*
        Call ContinueWeatherList
    Else
        MsgBox "Thank you for you input.", vbInformation
    End If

End If

End Sub

like image 642
J VBA Avatar asked Oct 19 '22 05:10

J VBA


1 Answers

Try the code below. You need to setup a variable to get the feedback from the VBYesNo MsgBox.

Option Explicit

Sub ContinueWeatherList()

Dim Weather As String
'Assigning a Message Box result as a Variable for Yes/No    
Dim MoreWeather As Variant

' add label to restart to
ContinueWeatherList_Restart:
Weather = InputBox("Type in the weather for " & Range("C1").End(xlDown) + 1)

If Weather = "" Then
    MsgBox ("No data entered. Your response has not been recorded"), vbExclamation
Else
    Range("C1").End(xlDown).Offset(1, 0).Value = Range("C1").End(xlDown) + 1
    Range("A1").End(xlDown).Offset(1, 0).Value = Range("A1").End(xlDown) + 1
    Range("B1").End(xlDown).Offset(1, 0).Value = Weather
    Columns("A:C").EntireColumn.AutoFit
    MoreWeather = MsgBox("Thank you for entering your data " & vbNewLine & "Would you like to enter another?", vbYesNo)

    'Using IF statement to decide what happens for each condition
    If MoreWeather = vbYes Then
        ' use GOTo command and label to reinitiate the sub
        GoTo ContinueWeatherList_Restart
    Else
        MsgBox "Thank you for you input.", vbInformation
    End If

End If

End Sub
like image 124
Shai Rado Avatar answered Oct 21 '22 00:10

Shai Rado