VBA – 重复msgbox

我是新来的,所以请裸露在我身上。 我已经创build了3个combobox,如下所示,从列表框中生成结果。 如果三个combobox中的任何一个留空,我想生成一个错误框。 但是,我写的代码会生成多个错误信息框。 我如何解决这个问题,所以msgbox只出现一次?

Private Sub Generateresults_Click() Dim x As Integer Dim i As Integer Dim j As Integer Dim p As Integer p = Sheets("Training1A").UsedRange.Rows.Count Sheets("Results").Range("A2:P" & p).ClearContents x = 2 For i = 0 To Me.Listtest.ListCount - 1 If Me.Searchoption = "AND" Then If Me.Listtest.Column(1, i) = Search1 And Me.Listtest.Column(2, i) = Search2 Then For j = 0 To 9 Sheets("results").Cells(x, j + 1) = Me.Listtest.Column(j, i) Next j x = x + 1 Else x = x End If ElseIf Me.Searchoption = "OR" Then If Me.Listtest.Column(1, i) = Search1 Or Me.Listtest.Column(2, i) = Search2 Then For j = 0 To 9 Sheets("results").Cells(x, j + 1) = Me.Listtest.Column(j, i) Next j x = x + 1 Else x = x End If ElseIf Me.Searchoption = "ALL" Then For j = 0 To 9 Sheets("results").Cells(x, j + 1) = Me.Listtest.Column(j, i) Next j x = x + 1 Else x = x **If Searchoption = "" Or Search1 = "" Or Search2 = "" Then MsgBox "Select an option" End If** End If Next i End Sub 

如果你想在拖出第一个MsgBoxExit Sub ,把Exit Sub放在它下面。

 If Searchoption = "" Or Search1 = "" Or Search2 = "" Then MsgBox "Select an option" Exit Sub End If 

否则, MsgBox调用在For...Next循环体内部,它将在满足条件的每个迭代中重复。

如果您需要在NextEnd Sub之间运行更多代码(不pipe是否显示MsgBox ),那么您也可以Exit For ,退出循环但保留在过程中:

 If Searchoption = "" Or Search1 = "" Or Search2 = "" Then MsgBox "Select an option" Exit For End If