Excel VBA运行时错误13 – 当框为空时不匹配

我被困在VBA中。 我曾尝试在网站上的其他解决scheme,但仍然无法做到正确。 我正在使用多个模块和表单来获取一些信息input到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 

结束小组

如果您希望用户仅input数字input,则使用Application.InputBox Type:=1 Application.InputBox

 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 

将qtyGateFees更改为Variant:

 Dim qtyGateFees As Variant 

我相信你会得到一个types不匹配的错误,因为你试图给一个变暗的variables指定一个空值为“Double”。

你可以试试这个,而不是isNull:

 If qtyGateFees = "" Then 

您可以使用error handling(无论如何这是一个很好的做法),而不是将variables声明为Variant

 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