如果x是整数,在VBA语言中如何表达? 我想编写一个代码,如果 x 是整数,则执行某些操作;如果不是使用 vba excel,则执行其他操作。
Sub dim()
Dim x is Variant
'if x is integer Then
'Else:
End Sub
If IsNumeric(x) Then 'it will check if x is a number
如果你想检查类型,你可以使用
If TypeName(x) = "Integer" Then
这可能适合:
If x = Int(x) Then
这取决于您的意思是数据类型“整数”,还是“没有小数的数字”意义上的整数。如果您指的是后者,那么快速手动测试就足够了(参见第一个示例);如果您的意思是前者,那么可以通过三种方法来查看数据类型,每种方法都有不同的优缺点:
Public Sub ExampleManual()
Dim d As Double
d = 1
If Fix(d) = d Then
MsgBox "Integer"
End If
End Sub
Public Sub ExampleTypeName()
Dim x As Integer
MsgBox TypeName(x)
End Sub
Public Sub ExampleTypeOf()
Dim x As Excel.Range
Set x = Selection
''//Using TypeOf on Objects set to Nothing will throw an error.
If Not x Is Nothing Then
If TypeOf x Is Excel.Range Then
MsgBox "Range"
End If
End If
End Sub
Public Sub ExampleVarType()
Dim x As Variant
''//These are all different types:
x = "1"
x = 1
x = 1&
x = 1#
Select Case VarType(x)
Case vbEmpty
Case vbNull
Case vbInteger
Case vbLong
Case vbSingle
Case vbDouble
Case vbCurrency
Case vbDate
Case vbString
Case vbObject
Case vbError
Case vbBoolean
Case vbVariant
Case vbDataObject
Case vbDecimal
Case vbByte
Case vbUserDefinedType
Case vbArray
Case Else
End Select
End Sub
所有答案都不适合我。 如果输入是任何 EG 字符串,那么此代码可以安全运行,不会出现错误:
Function IsInt(s As String) As Boolean
Dim res As Boolean: res = False
If IsNumeric(s) Then
res = (s = Int(s))
End If
IsInt = res
End Function
注意:显然 VBA 没有短路评估 (SCE),因此您需要在这里使用 if-then 语句。
我不喜欢 SCE 的缺失,但至少现在我有一个例子可以向我的朋友和同事展示,他们认为所有语言都有 SCE,尽管支持和反对都有争论。