有人可以告诉我为什么我收到错误'对象要求'在VBA中运行此代码?对不起,这是我第一次写VBA代码..
Public Sub FinalScore()
Dim E1, E2, E3, E4, GP, FE As Long
Dim strOutput, G As String
Dim S As Double
Dim Fail, Pass, Merit, Distinction As String
E1 = InputBox("What is your result of 1st excecise?", "question1")
If Not IsNumeric(E1.Value) Then
MsgBox "Sorry bro I need a number not a String"
E1.SetFocus
Else
If E1 < 0 And E1 > 10 Then
MsgBox ("Input number must be in between 0 and 10")
E1.SetFocus
End If
End If
End Sub
答案 0 :(得分:2)
E1
是Variant
类型,目前包含InputBox
函数的结果,它通常会返回一个字符串。由于不是对象,因此它会在E1.Value
和E1.SetFocus
上引发错误,因为它没有任何此类方法或属性。
.SetFocus
方法与Form Control
个对象有关,不会将用户返回到输入框。
您可以使用GoTo
语句来控制流量并强制用户输入正确的类型/值:
ReTry:
E1 = InputBox("What is your result of 1st excecise?", "question1")
If Not IsNumeric(E1) Then
MsgBox "Sorry bro I need a number not a String"
GoTo ReTry
Else
If E1 < 0 And E1 > 10 Then
MsgBox ("Input number must be in between 0 and 10")
GoTo ReTry
End If
End If
另请注意,您的变量隐式输入为Variant
。在以下示例中,只有z
被强类型化为String
数据类型。其他人没有明确的类型,因此他们将被视为Variant
。
Dim x, y, z as String
建议和良好做法输入每个变量:
Dim x as String
Dim y as String
Etc...