3

我被困在VBA中。我在网站上尝试了其他解决方案,但仍然无法正确解决。我正在使用多个模块和表单将一些信息输入到 Excel 的单元格中。但是,当 msgBox 留空时,它会给我一个 13 型不匹配错误。我尝试过 isNull 但不完全了解如何使用它。

任何帮助将不胜感激,并且请尽可能简单地回答任何问题,因为我充其量只是一个新手程序员。谢谢

Sub GetEndCostGateFees()
    Dim qtyGateFees As Double
    Dim msg As String

Const MinCost As Integer = 0
Const MaxCost As Integer = 200

msg = "Please enter the cost, per tonne, of Gate fees "

Do
    qtyGateFees = InputBox(msg, "Gate Fees")

    If IsNull(qtyGateFees) Then
        MsgBox ("Please enter a value. Enter 0 if none")
        End If

    If IsNumeric(qtyGateFees) Then
        If qtyGateFess >= MinCost And qtyGateFees <= MaxCost Then Exit Do
        End If
        msg = "Please enter a valid number"
        msg = msg & vbNewLine
        msg = msg & "Please enter number between " & MinCost & " and " & MaxCost
        Loop

Sheet25.Range("B43").Value = qtyGateFees

结束子

4

3 回答 3

4

如果您希望用户仅输入数字输入,请使用Application.InputBoxwithType:=1

Sub sample()
    Dim Ret As Variant
    Dim msg

    msg = "Please enter the cost, per tonne, of Gate fees "

    Ret = Application.InputBox(msg, "Gatefees", Type:=1)

    If Ret <> False Then
        '
        '~~> Rest of your code here
        '
    End If
End Sub
于 2013-10-17T14:02:45.643 回答
0

Variant您可以使用错误处理(无论如何这是一个好习惯),而不是将您的变量声明为 a 。

Option Explicit
    Sub GetEndCostGateFees()
        Dim qtyGateFees As Double
        Dim msg As String

        Const MinCost As Integer = 0
        Const MaxCost As Integer = 200

        msg = "Please enter the cost, per tonne, of Gate fees "

        Do
            On Error GoTo TypeM
            qtyGateFees = InputBox(msg, "Gate Fees")
            On Error GoTo 0

            If IsNumeric(qtyGateFees) Then
                If qtyGateFees >= MinCost And qtyGateFees <= MaxCost Then Exit Do
            End If
            msg = "Please enter a valid number"
            msg = msg & vbNewLine
            msg = msg & "Please enter number between " & MinCost & " and " & MaxCost
        Loop

        Sheets(Sheet25).Range("B43").Value = qtyGateFees

    Exit Sub

        TypeM:
        If Err.Number = 13 And Err.Description = "Type mismatch" Then
            MsgBox "Please enter a value. Enter 0 if there were no fees."
            Err.Clear
            Resume
        Else
            Debug.Print Err.Number & " " & Err.Description
        End If

    End Sub
于 2013-10-17T14:15:03.150 回答
0

将 qtyGateFees 更改为 Variant:

Dim qtyGateFees As Variant

我相信您会收到类型不匹配错误,因为您试图将空白值分配给一个变暗为“Double”的变量。

然后你可以试试这个而不是 isNull:

If qtyGateFees = "" Then
于 2013-10-17T13:58:14.977 回答