对不同的数据类型使用相同的变量

时间:2013-07-02 12:29:17

标签: vba variable-declaration

我想使用具有相同变量的不同数据类型并进行一些计算。 例如,我正在使用变量"选项"在,

If option = 1 then
   Do this
Elseif option = "X" then
   Do this
Elseif option = 6 then
   Do this
Endif

有什么方法可以让这个工作吗?

2 个答案:

答案 0 :(得分:2)

您可以使用变量来允许一个变量内的不同数据类型。以下代码有效。

Public Sub TestVariant()
  Dim x As Variant

  x = 17

  If x = 1 Then
    ' Do this
  ElseIf x = "bob" Then
    ' Do this
  ElseIf x = 17 Then
    ' This is done
  End If
End Sub

离开我的头顶,这有点闻起来。最好严格定义变量。如果您正在处理也可能是字符串的数字,您可以随时将数字转换为字符串。例如:

Public Sub TestVariant()
  Dim x As string

  x = "1"

  If x = "1" Then
    ' Do this
  ElseIf x = "bob" Then
    ' Do this
  ElseIf x = "17" Then
    ' This is done
  End If
End Sub

编辑:另一个在Excel中按预期编译和工作的示例。

Public Function TestVariant(theOption As Variant)
  If theOption < 0 Then
    TestVariant = "Negative"
  ElseIf theOption = 6 Then
    TestVariant = "Six"
  ElseIf theOption = "Stuff" Then
    TestVariant = "Other Stuff"
  Else
    TestVariant = theOption
  End If
End Function

答案 1 :(得分:1)

如果您将option声明为Variant,那么您应该好好去。

相关问题