Excel VBA Runtime error 13 - несоответствие, когда поле пусто
Я застрял в 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
End Sub
3 ответа
Если вы хотите, чтобы пользователь вводил только числовой ввод, используйте Application.InputBox
с Type:=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
Измените qtyGateFees на вариант:
Dim qtyGateFees As Variant
Я считаю, что вы получаете ошибку несоответствия типов, потому что вы пытаетесь присвоить пустое значение переменной, которая dim'd как "Double".
Вы можете попробовать это вместо isNull:
If qtyGateFees = "" Then
Вместо того, чтобы объявить вашу переменную как 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