简体   繁体   中英

VBA Exit Sub in Userform without saving previously completed fields to sheet

I have a VBA based Userform housed in Excel which I am having difficulty in applying some logic. The Userform is to collect data, and store it in a sheet on the Excel file.

In the form, there are four radio buttons, under the comment "Four conditions which must be met" below. I wish to have all four of these buttons selected before the user can submit the form. The lower half of the code works well as expected, ie the user must select all four options, and if they have not, the sub exits and they are sent back to the form.

However, the issue is that each time they are sent back to the form, the other values within the form, eg the text boxes in the upper half of the code are saved into the sheet.

Is there any way the sub can exit, send the user back to the form for correct completion, and not save all previous completed fields into my database sheet? Been stuck on this for a few hours!

Thank you!

' Three demographic pieces of information
    .Cells(lRow, 8).Value = TextBox6.Value
    .Cells(lRow, 9).Value = TextBox7.Value
    .Cells(lRow, 10).Value = TextBox8.Value
    
' Four conditions which must be met
    If OptionButton4.Value = True And OptionButton5.Value = True And OptionButton6.Value = True And OptionButton7.Value = True Then
        .Cells(lRow, 11).Value = "Completed"
        .Cells(lRow, 12).Value = "Completed"
        .Cells(lRow, 13).Value = "Completed"
        .Cells(lRow, 14).Value = "Completed"
    ElseIf OptionButton4.Value <> True Or OptionButton5.Value <> True Or OptionButton6.Value <> True Or OptionButton7.Value <> True Then
         MsgBox "Please ensure the four condition boxes are checked"
         Exit Sub
    End If

A good strategy is to abstract decisions like "OK to save?" into a separate piece of code which is re-usable:

If OKToSave Then  'call your function

    ' Three demographic pieces of information
    .Cells(lRow, 8).Value = TextBox6.Value
    .Cells(lRow, 9).Value = TextBox7.Value
    .Cells(lRow, 10).Value = TextBox8.Value
    'other info...
    .Cells(lRow, 11).Value = "Completed"
    .Cells(lRow, 12).Value = "Completed"
    .Cells(lRow, 13).Value = "Completed"
    .Cells(lRow, 14).Value = "Completed"

Else
    MsgBox "Please ensure the four condition boxes are checked"
    Exit Sub
End If

Your "business rule" is a function:

Function OKToSave() As Boolean
    OKToSave = OptionButton4.Value = True And OptionButton5.Value = True And _
               OptionButton6.Value = True And OptionButton7.Value = True
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM