Bpk7
Bpk7

Reputation: 89

VB - Index outside of bounds?

Oh my god i hate this thing, i tried millions of ways but couldn't find a working one. Let me explain:

I'm testing each line and checking the first word to be "copy" alright ? After the word copy i want to see if the next word is "1" , the third is "<" and the last is ">" , if all these conditions are fullfilled then the text between "<" and ">" needs to be stored in the variable "copy1" (even if there is more than 1 word between them).

What my code is:

For i = 0 To lstCode.Items.Count - 1

Dim str As String = lstCode.Items.Item(i)

Dim strA() As String = Split(str)

Dim copy1 as string

Dim copy2 as string

Select Case strA(0)


Case copy


If strA(1) = "1" And strA(2) = "<" And strA(strA.Count - 1) = ">" Then

copy1 = ""

For lr As Integer = 3 To strA.Count - 2

copy1 &= (strA(lr) & " ")

Next

End if

End select

And, when i debug it i get the error: Index was outside the bounds of the array ... Does anybody have any idea ?


There is something important i forgot to add, this is the whole code:

 Case "copy"

                    If strA(1) = "1" And strA(2) = "<" And strA(strA.Count - 1) = ">" Then
                        copy1 = ""

                        For lr As Integer = 3 To strA.Count - 2
                            copy1 &= (strA(lr) & " ")
                        Next


                    ElseIf strA(1) = "2" And strA(2) = "<" And strA(strA.Count - 1) = ">" Then
                        copy2 = ""

                        For lrs As Integer = 3 To strA.Count - 2
                            copy2 &= (strA(lrs) & " ")
                        Next



                    ElseIf strA(1) = "run" Then
                        Try
                            IO.File.Copy(copy1, copy2)
                        Catch ex As IO.IOException
                        End Try
                    End If


            End Select

So everything works like a charm: copy 1 < c:\csb.log > , copy 2 < c:\blabla.txt > but when the " copy run " statement comes in it gives me the error...

Upvotes: 0

Views: 560

Answers (1)

Steve
Steve

Reputation: 216243

You need to change the operator And with AndAlso.

The second one applies Short Circuit Evaluation to your expression, meaning if the first expression is false the second, third and so on expressions on the same line are not evaluated.

In your line

 If strA(1) = "1" And strA(2)  = "<" And .......

when the value is "Run" you still evaluate the expression strA(2) = "<" but there is no element at index 2 so you get the error.

Upvotes: 1

Related Questions