Simonetos Simonetos - 6 months ago 10
Vb.net Question

VB.NET - Increase variables in For statement

I have this part of code into a visual basic project...

Dim fileReader1 = My.Computer.FileSystem.ReadAllText(openFileDialog1.FileName)
Dim Part1A = "<b id=""Blahblah"">"
Dim Part1B = "</b>"
Dim fileSplit1 = fileReader1.Split(New String() {Part1A}, StringSplitOptions.None)
fileReader1 = fileSplit1.Last
fileSplit1 = fileReader1.Split(New String() {Part1B}, StringSplitOptions.None)
fileReader1 = fileSplit1.First


...and I am trying to make a loop for it to increase number
1
for all variables. Something like this...

For i As Integer = 1 To 10
Dim ("fileReader" & i) = My.Computer.FileSystem.ReadAllText(openFileDialog1.FileName)
...
Next


...but I get errors! Any idea how should be the syntax?

Answer

Unfortunately, variables do not like to be named like this. However, you could use an array:

Dim fileReader(10) as String

For i As Integer = 1 To 10
    fileReader(i) = My.Computer.FileSystem.ReadAllText(openFileDialog1.FileName)
    Dim Part1A = "<b id=""Blahblah"">"
    Dim Part1B = "</b>"
    Dim fileSplit1 = fileReader(i).Split(New String() {Part1A}, StringSplitOptions.None)
    fileReader(i) = fileSplit1.Last
    fileSplit1 = fileReader(i).Split(New String() {Part1B}, StringSplitOptions.None)
    fileReader(i) = fileSplit1.First
Next

The rest of your code would be fine, you would just need to change every instance of fileReader1 to fileReader(i).

If it is necessary for Part1A and Part1B to be have unique values for each i, you would make an array in the same way:

Dim fileReader(10) as String
Dim PartA(10) as String
Dim PartB(10) as String

For i As Integer = 1 To 10
    fileReader(i) = My.Computer.FileSystem.ReadAllText(openFileDialog1.FileName)
    Dim PartA(i) = "<b id=""Blahblah"">"
    Dim PartB(i) = "</b>"
    Dim fileSplit1 = fileReader(i).Split(New String() {PartA(i)}, StringSplitOptions.None)
    fileReader(i) = fileSplit1.Last
    fileSplit1 = fileReader(i).Split(New String() {PartB(i)}, StringSplitOptions.None)
    fileReader(i) = fileSplit1.First
Next

It is unnecessary, however, to put PartA and PartB into arrays if they will always have the same value, which they will have in the example you gave. If the example remains the way it is, it is only necessary to change fileReader1 to fileReader(i).

Comments