Endif must be preceded by a matching if

Wol*_*ves 5 vb.net if-statement sortedlist

I have a piece of vb.net code that I wrote. It's a for loop with two embedded if statements, and the compiler is telling me that each elseif and endif must be preceded by a matching if.

This is my second day of working with vb.net ever, and the only programming experience I have is writing .bat files, so this could be something really stupid. But I cannot figure out why I'm getting these errors, and if you all would be willing to help me out, I would greatly appreciate it!

For Each computer In compArray
        If compArray(I) <> Computers.GetKey(I) Then notpresentList.Add(Computers.GetKey(I)) 
Else 
        If Computers.GetByIndex(I) = 0 Then disabledList.Add(Computers.GetKey(I))
        Elseif Computers.GetByIndex(I)=1 Then enabledList.Add(Computers.GetKey(I))
        Elseif Computers.GetByIndex(I)=2 Then unknownList.Add(Computers.GetKey(I))
    End if
    End if
        I += 1
    Next
Run Code Online (Sandbox Code Playgroud)

The context for this: I am trying to write a piece of code that will confirm the presence of bitlocker. I wrote in VBScript something that will check whether bitlocker is enabled and then send an email. This piece of code is a part of a program which would retrieve those emails, compare them to a list of computers, and then produce a digest email which states which computers are absent, have bitlocker enabled, disabled, or in an unknown state.

我敢肯定还有另一种更好的方法可以做到这一点,但是正如我所说的,我对此还很陌生,出于法律原因,我们需要这样做。

再次感谢!

编辑:如果您需要更多信息,请问我!

Jay*_*Jay 5

您的If…Then台词需要分解。将所有内容移至Then下一行,您应该会很好。

If compArray(I) <> Computers.GetKey(I) Then notpresentList.Add(Computers.GetKey(I)) 
Run Code Online (Sandbox Code Playgroud)

If…Then一行上的语句是独立的,不以结尾结尾End If,也不能使用ElseIf


Tim*_*ter 5

我只会在简短的条件下在VB.NET中使用内联语法。否则,它将使代码的可读性降低,并且更容易出错。

尝试这个:

For Each computer In compArray
    If compArray(i) <> Computers.GetKey(i) Then
        notpresentList.Add(Computers.GetKey(i))
    Else
        Dim comp = Computers.GetByIndex(i)
        If comp  = 0 Then
            disabledList.Add(Computers.GetKey(i))
        ElseIf comp = 1 Then
            enabledList.Add(Computers.GetKey(i))
        ElseIf comp = 2 Then
            unknownList.Add(Computers.GetKey(i))
        Else ' added this to show you that this case is not covered yet
            Throw New NotSupportedException
        End If
    End If
    i += 1
Next
Run Code Online (Sandbox Code Playgroud)

  • 可以使用内联语法,但是仅适用于简短的简单语句。这个块既不短也不简单:) (4认同)