Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

excel - VBA - How to create a multistep verification If statement?

I have the following userform:

enter image description here

At this moment, I have several message boxes that make sure all necessary fields are completed/selected.

Example #1:

If CheckBox4 is Selected -> Is Number Box 4 or Text Box 4 selected? -> If not, there's a MsgBox warning.

If CheckBox4 is Selected -> is Weight Box 4 field empty? -> If yes, there's a MsgBox warning.

If Number box 4 is selected -> Is Normalization Box 4 selected? -> If not, there's a MsgBox warning.

Example code of one of this warnings:

' Make sure if additional metrics are selected : number or text is selected

If CheckBox1 = True And (NumBox1 = False And TxtBox1 = False) Then
    MsgBox ("Please define if the metric is numerical or text.")
    Exit Sub
End If

If CheckBox2 = True And (NumBox2 = False And TxtBox2 = False) Then
    MsgBox ("Please define if the metric is numerical or text.")
    Exit Sub
End If

(...)

It works and does the job, but it's a lot of code. Ideally I'd like to find a way to compile all these "warnings" into a single MsgBox.

Additional info:

CheckBox1 / NumBox1 / TxtBox1 / NorBox1 / WBox1

CheckBox2 / NumBox2 / TxtBox2 / NorBox2 / WBox2

etc.

These are the names attributed to each control.

Tbh, I have no idea how to go on this since I'm veeeeery new to VBA. Any help you can give me is really appreciated. :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For someone who thinks he's still new to VBA i'd say you're getting along quite well already!

I didn't test my code below, but I'd go with .Controls("button/txtbox" & i) to put it into one code.

For i = 1 to 4 '1 and 4 represent the start and end if you have 20 checkboxes change 4 to 20. If the first number used is checkbox5, change 1 to 5 etc.
    With Userform1
        If .Controls("CheckBox" & i) = True And .Controls("NumBox" & i) = False And .Controls("TxtBox" & i) = False Then
            MsgBox ("Please define if the metric is numerical or text.")
            Exit Sub
        End If
    End With
Next

This will loop all the requirements, if something is False (so if a checkbox is not checked) no MsgBox should appear. But for all the checked boxes and the other criteria are false it should bring up the MsgBox like before and exit the sub.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
...