2017-05-05 49 views
0

我有這個代碼彈出一個消息框,要求用戶以mm/dd/yyyy格式輸入日期。點擊取消時,表示輸入有效日期。如果用戶取消該框,則消息框應該停止/消失。但我不知道該怎麼做。vb代碼 - 取消消息框

下面的代碼:

Try 
    Dim docDate As String 
    Dim batchNumber as String 
    Dim dDate As Date 
    Dim match As System.Text.RegularExpressions.Match 

    'Define the regular expression to check dates 
    Dim dateRegex As New System.Text.RegularExpressions.Regex(regExpression) 
    'Prompt for the document date 
    docDate = Microsoft.VisualBasic.Interaction.InputBox(「Enter the document date (mm/dd/yyyy):」, 「Document Date」) 
    'Match the input against the regex 
    match = dateRegex.Match(docDate) 

    'While it doesn't match the regex or a valid date continue to prompt for it 
    Do While (Not match.Success Or Not Microsoft.VisualBasic.IsDate(docDate)) 
     'Alert the user of the problem 
     Microsoft.VisualBasic.MsgBox(「Please enter a valid date in the format of mm/dd/yyyy.」) 
     'Prompt for the document Date 
     docDate = Microsoft.VisualBasic.Interaction.InputBox(「Enter the document date (mm/dd/yyyy):」, 「Document Date」) 
     'Match the input against the regex 
     match = dateRegex.Match(docDate) 
    Loop 

    'Store the input dates in Date datatypes 
    dDate = CDate(docDate) 
    'Set the value into the global variables 
    GBL_DOCUMENTDATE = dDate 
    GBL_BATCH = batchNumber 

Catch ex As Exception 
    If (mapInterface = 1) Then 
     Messagebox.Show(ex.Message, 「DateInputTemplate Script Error」) 
    End If 
    Return False 
End Try 
+3

使用DateTimePicker控件,你不必驗證任何東西。請閱讀[問]並參加[遊覽]。 – Plutonix

+2

...東西,東西,正則表達式,現在你有兩個問題... – LarsTech

+0

我建議閱讀精美的文檔,它會向你解釋當用戶選擇「取消」時InputBox的返回值。然後,相應地調整循環中的條件。 – Craig

回答

2
If MessageBox.Show("Please enter a valid date in the format of mm/dd/yyyy.", "Question", MessageBoxButtons.OKCancel) = DialogResult.OK 
    docDate = Microsoft.VisualBasic.Interaction.InputBox(「Enter the document date (mm/dd/yyyy):」, 「Document Date」) 
Else 
    'Do nothing? Get rid of the else statement if you don't need it 
End If 

所以這會彈出按鈕確定和取消一個消息框,如果用戶單擊確定,然後繼續在If語句塊中的代碼。

-1

這是我該怎麼做。

Dim valid as boolean 
    Do 
     valid = true 
     docDate = Microsoft.VisualBasic.Interaction.InputBox(「Enter the document date (mm/dd/yyyy):」, 「Document Date」) 
     match = dateRegex.Match(docDate) 
     If (docDate = "") 
      'they clicked cancel leave the loop 
      docDate = Date.Now().toString("MM\/dd\/yyyy") 
      Exit Do 
     ElseIf (Not match.Success Or Not Microsoft.VisualBasic.IsDate(docDate)) Then 
      valid = false 
      Microsoft.VisualBasic.MsgBox(「Please enter a valid date in the format of mm/dd/yyyy.」) 
     End If 
    Loop until valid 

所以會要求輸入文件日期。如果他們按取消而不是輸入日期,並且按docDate變爲空字符串,那麼if語句會檢查並將docDate設置爲今天的日期。 如果他們輸入日期並且輸入的日期不是有效的日期,那麼msgbox將會出現並且循環將再次開始並詢問文檔日期。