VBA文本框以数字值

我有这个代码,我需要文本框9和10,当进入我的Excel表中的数字vlaues任何想法如何我可以解决这个问题?

Sub FillRanges(ws As Worksheet, L As Long) With ws .Range("C" & L).Value = (Now) .Range("D" & L).Value = Me.TextBox2 .Range("E" & L).Value = Me.TextBox3 .Range("F" & L).Value = Me.TextBox4 .Range("G" & L).Value = Me.TextBox5 .Range("K" & L).Value = Me.ComboBox1 .Range("L" & L).Value = Me.ComboBox2 .Range("M" & L).Value = Me.ComboBox3 .Range("N" & L).Value = Me.TextBox9 .Range("O" & L).Value = Me.TextBox10 .Range("R" & L).Value = Me.TextBox39 .Range("P" & L).Value = Me.TextBox40 End With 

结束小组

我认为最好在使用(写)它之前validation用户input

所以你可能想写一些非常简单的用户inputvalidation潜艇,并从控制内更改事件处理程序调用它们,如下所示:

 Option Explicit Private Sub TextBox9_Change() ValidateNumericInput Me.TextBox9, 0, 10.4 '<--| as soon as this control text changes, call 'ValidateNumericInput' to validate it End Sub Private Sub ValidateNumericInput(tb As MSForms.TextBox, minVal As Double, maxVal As Double) Dim errMsg As String With tb If Len(.Text) > 0 Then '<-- proceed only if there's some text to validate! Select Case True Case Not IsNumeric(.value) '<--| if not a "numeric" input errMsg = "please enter a number" Case CDbl(.Text) < minVal Or CDbl(.Text) > maxVal '<--| if "numeric" input exceeds passed range errMsg = "please enter a number within " & minVal & " and " & maxVal End Select If errMsg <> "" Then '<--| if error message has been written MsgBox "invalid input in " & tb.name & vbCrLf & vbCrLf & errMsg, vbCritical + vbExclamation + vbOKOnly, "Invalid input" '<--| infrm the user .Text = "" '<--| delete textbox input End If End If End With End Sub 

在那里我假定一个Doubletypes的input将是需要的,但你可以很容易地适应其他types

所以,你可能会添加如下的其他子目录:

 ValidateStringInput(tb As MSForms.TextBox, validStrings() as String) 

和喜欢…

您可以使用CDbl()等转换函数。 这将是这样的:

 Sub FillRanges(ws As Worksheet, L As Long) With ws .Range("C" & L).Value = (Now) .Range("D" & L).Value = Me.TextBox2 .Range("E" & L).Value = Me.TextBox3 .Range("F" & L).Value = Me.TextBox4 .Range("G" & L).Value = Me.TextBox5 .Range("K" & L).Value = Me.ComboBox1 .Range("L" & L).Value = Me.ComboBox2 .Range("M" & L).Value = Me.ComboBox3 .Range("N" & L).Value = CDbl(Me.TextBox9) .Range("O" & L).Value = CDbl(Me.TextBox10) .Range("R" & L).Value = Me.TextBox39 .Range("P" & L).Value = Me.TextBox40 End With 

还有其他的转换function。 CInt() (整数), CLng() (长)和CDec() (十进制)。