• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

How to exit from macro after N number of failed attempts

ThrottleWorks

Excel Ninja
Hi,

In one of my macro, I am providing user an option to select folder path.
If user does not select folder path, macro goes back to label ‘MyFolderSelect:’ and re-prompts user.

This action is cycled till user selects a folder.

However, there might be an occasion where wants to close macro file without running the macro. However my ‘MyFolderSelect’ line will not allow him to do so.

Is there any option to check if user does not select folder path for 3-5 instances, macro should not go back to label and stop running.
Can anyone please help me in this.

Code:
Dim strPath As String
MyFolderSelect:
    strPath = SelectFile(ThisWorkbook.Worksheets("Mapping").Range("D2").Value, True)
    If Len(strPath) > 0 Then
            ThisWorkbook.Worksheets("Mapping").Range("D2").Value = strPath & "\"
            strPath = strPath & "\"
        Else
            MsgBox "You have not selected any foder"
            GoTo MyFolderSelect:
    End If
 
Hi,

Perhaps using a counter, something like this:
Code:
Dim strPath As String
Dim counter As Integer

counter = 0
MyFolderSelect:
    strPath = SelectFile(ThisWorkbook.Worksheets("Mapping").Range("D2").Value, True)
    If Len(strPath) > 0 Then
            ThisWorkbook.Worksheets("Mapping").Range("D2").Value = strPath & "\"
            strPath = strPath & "\"
        Else
            MsgBox "You have not selected any foder"
            counter = counter + 1
            If counter < 4 Then
                    GoTo MyFolderSelect:
                Else
                    MsgBox "Maximum attempts reached: 5!" & vbCrLf & "Closing..."
                    Exit Sub
            End If
    End If

Untested... but should work :)

Hope this helps
 
Back
Top