2017-05-09 83 views
0

在我的用戶表單中我想MsgBox如果文本框不包含數字或空。 這是我的代碼,但在另一種情況下TextBox = ""空MsgBox對我來說,所以我的問題是空的TextBox。VBA用戶窗體文本框只允許數字和空文本

Private Sub TB1_Change() 
    If TypeName(Me.TB1) = "TextBox" Then 
     With Me.ActiveControl 
      L12.Caption = Val(TB1.Text) * Val(TB2.Text) 
      If Not IsNumeric(.Value) And .Value <> vbNullString Then 
       MsgBox "Sorry, only numbers allowed" 
       .Value = vbNullString 
      End If 
     End With 
    End If 
End Sub 
+0

什麼'MsgBox「對不起,只允許輸入數字,但是輸入'」&.Value&「'。」'寫入'''之間? –

+0

對不起,我不明白的味精:) –

+1

用我貼的代碼替換你的MsgBox代碼。運行你的代碼,並告訴我們當你的文本框爲空時MsgBox中的內容。 –

回答

2

爲此使用Key Press事件。

Private Sub TB1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) 
    If Not IsNumeric(Chr(KeyAscii)) Then KeyAscii = 0 
End Sub 

如果不是數字,此過程將忽略任何輸入,但可以修改條件和輸出。例如,您可能允許輸入小數點,或者您可能希望顯示一個消息框 - 可能僅在第二次嘗試時顯示。

0

由於您試圖只允許「數字」和「空白」,那麼下面的代碼將提供您的需求。

Private Sub TB1_Change() 
    if IsNumeric(Me.TB1.Value) = True or Me.TB1.Value = vbNullString then 
     'Good data, nothing to MSG 
    Else 
     MsgBox "Your input data is not valid" 
    Endif 
End Sub 
+0

你的答案當然值得一點解釋。請參閱http://stackoverflow.com/help/how-to-answer。評論有助於創建可搜索的內容。 –

0

您可以使用AfterUpdate事件處理代替Change事件,可能還需要使用Exit事件,並取消退出如果用戶輸入一個無效的值:

Option Explicit 
Private Sub TB1_AfterUpdate() 
    'Check whether the value is numeric or empty: 
    If Not IsValNumeric(Me.TB1.Value) Then 
     MsgBox "Sorry, only numbers allowed" 
     Me.TB1.Value = vbNullString 

    Else: 
     'Do something... 
     MsgBox val(TB1.Text) * val(TB2.Text) 
    End If 
End Sub 
Private Sub TB1_Exit(ByVal Cancel As MSForms.ReturnBoolean) 
    'Prevents the user from EXIT the TextBox if value is not numeric/empty 
    Cancel = Not IsNumeric(Me.TB1.Value) 
End Sub 
Private Function IsValNumeric(val$) As Boolean 
    Dim ret As Boolean 
    'check for numeric value only and allow empty value as a zero value 
    ret = IsNumeric(val) Or Len(val) = 0 
    IsValNumeric = ret 
End Function 
0

你可以等到用戶完成輸入然後測試該字段。

爲便於使用,應將消息框替換爲類似這樣的標題和圖標/圖片enter image description here「必須在此輸入一個數字。」

當輸入不正確時,這些將顯示在文本框旁邊。然後在輸入更正時隱藏。提交表格可以被阻止,直到所有錯誤得到糾正。

這允許用戶輸入請求數據,然後修復任何輸入錯誤。這比每次他們犯錯時停止它們要好。

活動從變更變爲退出

Private Sub TB1_Exit(ByVal Cancel As MSForms.ReturnBoolean) 
    If TypeName(Me.TB1) = "TextBox" Then 
     With Me.ActiveControl 
      L12.Caption = Val(TB1.Text) * Val(TB2.Text) 
      If Not IsNumeric(.Value) Or .Value = vbNullString Then 
       MsgBox "Sorry, only numbers allowed" 
       .Value = vbNullString 
      End If 
     End With 
    End If 
End Sub 

vbNullString測試也已更新。