2015-03-13 19 views
3

我在用戶窗體的下拉框中有一個代碼。每當用戶離開下拉框時,代碼檢查用戶輸入的值是否正確(即與列表匹配)。如果沒有,它會觸發一個消息框。這裏是我的代碼:使用「取消」或「X按鈕」退出用戶表單時禁用_Exit事件

Private Sub CmboxModifyRoute_Exit(ByVal Cancel As MSForms.ReturnBoolean) 

UserValue = CmboxModifyRoute.Value 
counter = 0 
Cell = Range("C15").Value 

If UserValue = "" Then Exit Sub 

Do While (counter < 35 And Cell <> UserValue) 'checking if UserValue is valid 
    counter = counter + 1 
    Cell = Range("C15").Offset(counter, 0).Value 
Loop 

If counter > 34 Then 'if invalid, then display message box 
    MsgBox "Invalid", vbExclamation 
End If 

End Sub 

當我用「X」按鈕或「取消」按鈕退出用戶窗體時會出現問題。如果UserValue無效,則在我已經退出用戶窗體之後,它仍然顯示「無效」消息框。我不想要它,我只想要用戶窗體卸載。我該如何處理這個問題?非常感謝!

回答

3

改變你的條件是:

If Me.Visible And counter > 34 Then 
    MsgBox "Invalid", vbExclamation 
End If 

然後如果窗體是不可見的將不被顯示的消息。

3

數據驗證應該在組合框的BeforeUpdate事件中進行。在用戶表單的Terminate事件之前,更新不會觸發。將UserForm_TerminateCmboxModifyRoute_BeforeUpdate事件添加到您的代碼中,在各自的聲明中設置斷點,並觀察調試模式下發生的事件順序。

Private Sub CmboxModifyRoute_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean) 
    'data validation goes here 
    'doesn't fire when the form is closed 
End Sub 

Private Sub CmboxModifyRoute_Exit(ByVal Cancel As MSForms.ReturnBoolean) 
    'this triggers before Terminate 
End Sub 

Private Sub UserForm_Terminate() 

End Sub