Elseif被跳过

我有我的excel文件中的以下内容

+----------+-------+---------------+ | Option | value | VisibleOption | +----------+-------+---------------+ | Option#1 | | #Option5 | | Option#2 | | #Option6 | | Option#3 | 3 | #Option7 | | Option#4 | 1200 | #Option8 | +----------+-------+---------------+ 

下面的函数被写入

 Private Sub CommandButton1_Click() Dim i As Integer Dim value_s As String i = 2 Do Until IsEmpty(Cells(i, 1)) value_s = ActiveSheet.Cells(i, 2) If value_s <> "" Then Debug.Print "value_s is not empty" ElseIf value_s = "1200" Then Debug.Print "value_s contains a 1200" Else Debug.Print "print the rest" End If i = i + 1 Loop End Sub 

现在,该函数返回以下内容

 print the rest print the rest value_s is not empty value_s is not empty 

虽然它应该返回类似于以下内容,因为1200是存在的:

 print the rest print the rest value_s contains a 1200 value_s is not empty value_s is not empty 

看来,ElseIf被跳过了。 这里出了什么问题?

如果语句在第一次成功的IF后closures,那么在你的实例中,只有当这个值为空时,才会到elseif,这样它会跳过它…所以它永远不会调用它。 要解决这个确切的例子,我会切换东西,如:

 If value_s == "" Then Debug.Print "print the rest" ElseIf value_s = "1200" Then Debug.Print "value_s contains a 1200" Else Debug.Print "value_s is not empty" End If 

更好的做法是:

 Select Case value_s Case "" Debug.Print "print the rest" Case "1200" Debug.Print "value_s contains a 1200" Case Else Debug.Print "value_s is not empty" End Select 

在这种情况下,您可以根据需要添加尽可能多的可能性。

我会写这样的ElseIf指令,我怀疑1200被存储为一个数字,你比较它是不一样的string“1200”。

 ElseIf value_s = 1200 Then 

添加到你的循环:

 debug.print ActiveSheet.Name debug.print value_s 

你会在即时窗口得到结果,你可以相应地修复。