VBA 文本框到数值

VBA Textbox to number value

我有这段代码,在输入 excel table 时,我需要将文本框 9 和 10 作为数字值 table 知道如何解决这个问题吗?

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

结束子

您可以使用像 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

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

我认为最好在使用(写入)之前验证用户输入

因此您可能想要编写一些非常简单的用户输入验证子程序并从控件 change 事件处理程序中调用它们,如下所示:

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

我假设需要 Double 类型的输入,但您可以轻松地将其适应其他 types

因此,您随后可以添加其他潜艇:

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

等等...