VB.NET Run command against 2 arrays - arrays

I have read 2 text files into 2 arrays and simply want to run a command which uses the 2 arrays.
Example:
part1.txt(array 1)
hxxp://somethinghere.com\1
hxxp://somethinghere.com\2
part2.txt(array 2)
Bob
James
myprogram.exe hxxp://somethinghere.com\1 Bob
myprogram.exe hxxp://somethinghere.com\2 James
I simply want to run a for loop which goes through both arrays, here's what I have so far:
Dim part1() As String = IO.File.ReadAllLines("C:\part1.txt")
Dim part2() As String = IO.File.ReadAllLines("C:\part2.txt")
For Each line As String In part1
MsgBox(line)
Next
EDIT:
Working code:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim part1() As String = IO.File.ReadAllLines("C:\part1.txt")
Dim part2() As String = IO.File.ReadAllLines("C:\part2.txt")
For parse As Integer = 0 To part1.GetUpperBound(0)
MsgBox(String.Concat("myprog.exe " & """" & part1(parse) & """" & " -arg1 " & """" & part2(parse) & ".txt" & """"))
Next
End Sub
So it will look like this:
myprog.exe "hxxp://somethinghere.com" -arg1 "Bob.txt"

How about something like this?
Private Sub testMethod()
Dim part1() As String = New String() {"one", "two", "three"}
Dim part2() As String = New String() {"10", "20", "30"}
For parse As Integer = 0 To part1.GetUpperBound(0)
Debug.Print(String.Concat("command ", part1(parse), part2(parse)))
Next
End Sub

Take a look at Enumerable.Zip:
Enumerable.Zip(Of TFirst, TSecond, TResult) Method
Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
So you could so something like
Dim part1() As String = IO.File.ReadAllLines("C:\part1.txt")
Dim part2() As String = IO.File.ReadAllLines("C:\part2.txt")
For Each element In part1.Zip(part2, Function(a, b) New With {a, b})
MsgBox(String.Format("{0} - {1}", element.a, element.b))
Next

First check that the arrays are the same length, then you can loop the indexes of one array and access the corresponding item in the other array.
To run the program you can use a ProcessStartInfo object to specify the parameters:
Dim part1() As String = IO.File.ReadAllLines("C:\part1.txt")
Dim part2() As String = IO.File.ReadAllLines("C:\part2.txt")
If part1.Length = part2.Length Then
For i As Integer = 0 To part1.Length - 1
Dim p As New ProcessStartInfo
p.FileName = "myprog.exe";
p.Arguments = """" & part1(i) & """ -arg1 """ & part2(i) & ".txt"""
Process.Start(p);
Next
Else
' Oops! different number of items in the files
' Tell the user
End If
You can set more properties in the ProcessStartInfo object to control how the program is started.

Related

VBA failing with array or user defined type expected

I have some code I am moving from VB.NET to VBA which has worked in the .NET world quite well. I have successfully moved almost all of the code into the VBA world with one exception thus far. Here is much of the code in question and all the variable declarations`
Dim vault As IEdmVault14
Dim eFile As IEdmFile9
Dim eFolder As IEdmFolder7
Dim pos As IEdmPos5
Dim Pathlist As EdmStrLst5
Dim parentFolder As IEdmFolder5
Dim vaultName As String
Dim filePath As String
Dim AssyName As String
Dim LoggedIn As Boolean
Set EdmVault5 = New EdmVault5
Set vault = New EdmVault5Dim fso As New FileSystemObject
Dim sw As TextStream
Set sw = fso.CreateTextFile("c:\temp\" & AssyName & ".txt")
'-----------------------------GET COLUMN HEADERS
Dim columns() As EdmBomColumn
BOM.GetColumns columns
Dim header As String
header = "LEVEL" & vbTab
Dim column As EdmBomColumn
For i = 0 To UBound(columns)
header = header & columns(i).mbsCaption & vbTab
Next
sw.writeline (header)
'-----------------------------Bom.READ EACH BOM ROW
Dim rows As Object
Dim row As IEdmBomCell
BOM.GetRows (rows)
For i = 0 To UBound(rows)
If IsNothing(row) Then Exit For
Dim rowString As String
Set rowString = row.GetTreeLevel.ToString & vbTab
Dim varVal As String
varVal = ""
For i = 0 To UBound(columns)
row.GetVar(column.mlVariableID, column.meType, varVal, Nothing, Nothing, Nothing)
If IsNothing(varVal) Then varVal = ""
rowString = rowString & varVal & vbTab
Next
'-----------------------------WRITE THE ROW TO THE FILE
sw.writeline (rowString)
Next
sw.Close
`
The array error occurs at BOM.GetRows (rows). I am stuck on what the issue could be. This error code does not occur in VB.NET but .NET does warn that Variable 'rows' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. I am not clear on how that translates into VBA if at all.
If anyone could shed some light on this it would be helpful I'm sure.
If you have a method signature (or function signature or whatever) that requires an array, then you have to Dim the variable you pass in as an array.
Public Sub test()
Dim x As Variant
Debug.Assert Not IsArray(x)
x = Array(1, 2)
Debug.Assert IsArray(x)
GetStuff x 'this fails
Stop
End Sub
Public Function GetStuff(a() As Variant) As Double
GetStuff = 1
End Function
Even though a Variant can hold an array, it doesn't pass the IsArray test just by declaring it. If I assign an array to it, it passes IsArray, but I still can't use it as an argument to function that requires an array. x is a Variant array and a() is an array of Variants. So the above code still won't compile.
It sounds from your comments that you got it sorted, but I thought I'd throw a little more information out there for posterity.

how to add some string to all array item?

I have an array like below
(0) = "apple"
(1) = "orange"
How can I add some string to all item in array? like apple become 'apple', orange become 'orange'
Edited
Private Sub test()
Dim txtReader As TextReader = New StreamReader("data.csv")
Dim parser = New CsvParser(txtReader)
Dim str As String = ""
'Ignore first line
parser.Read()
While True
Dim row = parser.Read()
If row Is Nothing Then
Exit While
End If
str &= $"({String.Join(",", row)}),"
End While
str_record = str.TrimEnd(",")
End Sub
Private Sub Model_Insert()
Dim data As String = ""
Dim query As String = "INSERT INTO main_item(item_code,item_name,item_desc,item_unitprice,item_barcode,dept_id,cat_id,gst_id,set_item,active)" &
"VALUES " & str_record & ""
Using cmd = New MySqlCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
End Sub
Im trying to create a string and use it in INSERT INTO
Use a For-loop:
Dim array = {"apple", "orange"}
For i As Int32 = 0 To array.Length - 1
array(i) = $"'{array(i)}'"
Next
If you can't use string interpolation yet, use String.Format (or string concatenation):
For i As Int32 = 0 To array.Length - 1
array(i) = String.Format("'{0}'", array(i))
Next
If you don't mind recreating the array, you could use Linq Select:
Dim testarray As String() = New String() {"orange", "apple"}
testarray = testarray.Select(Function(x) String.Format("'{0}'", x)).ToArray()

Access VBA loop through listbox select items and add to array

I'm trying to loop through a listbox and add the contents to an array....
My code is this:
Private Sub exportfolders_Click()
Dim list As String
Dim folderlist As String
Dim folderarray() As String
'Dim i As Interger
For i = 0 To Me.selectedfolders.ListCount - 1
'folderlist = (Me.selectedfolders.Column(0, i))
'folderarray() = Join(Me.selectedfolders.Column(0, i), ",")
list = (Me.selectedfolders.Column(0, i))
folderarray() = Join(list, ",")
ReDim Preserve folderarray(i)
Next i
folderlist = folderarray
'folderarray() = Join(folderlist, ",")
MsgBox (folderlist)
End Sub
You can see the bits I have commented out, trying all sorts to get it to work. But I keep getting the message "Can't assign to array" at folderarray(i) = Join(list, ","). Any pointers as to where I am failing?
You can concatenate the list box items into a string, and then use Split() to load your array. That way, the array is sized automagically without you needing to ReDim.
I tested this code in Access 2010:
Dim folderarray() As String
Dim i As Long
Dim strList As String
For i = 0 To Me!selectedfolders.ListCount - 1
strList = strList & "," & Me!selectedfolders.Column(0, i)
Next
' use Mid() to exclude the first comma ...
folderarray = Split(Mid(strList, 2), ",")
Note I don't know what you want to do with the array after loading it. MsgBox folderarray would throw Type mismatch error. MsgBox Mid(strList, 2) would be valid, but if that's what you want, you wouldn't need the array.
1) declare the array. Take a look at https://msdn.microsoft.com/en-us/library/wak0wfyt.aspx
2) No need of support variable
3) Assign the values to your array with the correct syntax
Private Sub exportfolders_Click()
Dim folderarray() As String
Dim i As Interger
Redim folderarray (Me.selectedfolders.ListCount-1)
For i = 0 To Me.selectedfolders.ListCount - 1
folderarray(i) = Me.selectedfolders.Column(0, i)
Next i
' Write here what you want to do with your array
End Sub
You could try something like this:
Private Sub ListToArray()
Dim folderArray() As Variant
Dim currentValue As String
Dim currentIndex As Integer
Dim topIndex As Integer
topIndex = Me.selectedfolders.ListCount - 1
ReDim folderArray(0 To topIndex, 0 To 1)
For i = 0 To topIndex
currentValue = Me.selectedfolders.Column(0, i)
folderArray(i, 0) = i
folderArray(i, 1) = currentValue
Next i
End Sub
Note my example is a multi-dimensional array which will give you the ability to add more than one item should you chose to do so. In this example I added the value of "i" as a placeholder/ index.

Regex expression and match function in text file

I have problem with my matching function actually I have to count number of lines with specific string and return line number ,so I have one dimensional array of string that contain the unique strings of text file {33,7,77,3 23,6} and text file with the same strings in array I have read lines of text file to array , but with duplicate of these strings ,when I use regex.match it works not bad expect when I check if line 2 contain 3 the function return True it's consider 3 in 23 as 3 , and the above explanation is just example of what I need any help please
Module Module1
Sub Main()
Dim txt As String = File.ReadAllText("e:\ii.txt")
' Use regular expressions to replace characters
' that are not letters or numbers with spaces.
Dim reg_exp As New Regex("[^a-zA-Z0-9]")
txt = reg_exp.Replace(txt, " ")
' Split the text into words.
'Dim words() As String = txt.Split( _
' New Char() {" "c}, _
' StringSplitOptions.RemoveEmptyEntries)
Dim words = txt.Split(New String() {" ", Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
' Use LINQ to get the unique words.
Dim word_query = _
(From word As String In words _
Order By word _
Select word).Distinct()
Dim stra() As String = word_query.ToArray()
For i = 0 To stra.Length - 1
Console.WriteLine(" " & stra(i))
Next
Dim lines() As String = IO.File.ReadAllLines("e:\ii.txt")
For i = 0 To lines.Length - 1
Console.WriteLine(lines(1))
Dim linecount = 0
Dim regex As New Regex(stra(i), RegexOptions.ExplicitCapture)
Dim match As Match = regex.Match(lines(1))
If match.Success Then
linecount += 1
Console.WriteLine("linecount= " & linecount)
Else
Console.WriteLine("false")
End If
Next
End Sub
End Module
You many not have to split the text into words. Is your word list very long? From what I understand you want the following:
1.Read a text file and return the line number for a given word or phrase.
Is the word or phrase complex? If not, why not use a the Contains extension method?
For example:
Dim myString = "Hello World"
If myString.Contains("World") Then
'Add line number to line count.
End if
If you are using this as an opportunity to learn regular expressions, I highly recommend "Mastering Regular Expressions" by Jeffrey Friedl. When I first begun I invested in a program RegexBuddy, which is worth the money. But now there are so many online regex testers now, that could be an alternative for something free.
Enhance your regex with anchors. These will ascertain that the whole test string matches instead of a substring. The following code also assembles all match patterns of interest into a single regex pattern which will be used against each line of the target file:
Dim strall As String
strall = ""
For i = 0 To stra.Length - 1
If i > o Then
strall = strall & "|"
End If
strall = strall & stra(i)
Console.WriteLine(" " & stra(i))
Next
strall = "^(" & strall & ")$"
Dim regexall As New Regex(strall, RegexOptions.ExplicitCapture)
'...
Dim linecount = 0
Dim match As Match = regexall.Match(lines(i)) '... was 'lines(1)', probably a typo
If match.Success Then
'...
this code is working with me thanks for all
Public Function countlines(ByVal st As String) As Integer
Dim count As Integer
Dim linecount As Integer = 0
Dim substrings() As String = Regex.Split(st, " ")
Dim stt() As String = {23, 7, 3}
For i = 0 To stt.Length - 1
'For j = 0 To substrings.Length - 1
'Console.WriteLine(substrings(0))
'For i = 0 To substrings.Length - 1
'Console.Write(substrings(i))
Dim matchQuery = From word In substrings Where word.ToLowerInvariant() = stt(i).ToLowerInvariant() Select word
' ' Count the matches.
count = matchQuery.Count()
Console.WriteLine("count=" & count)
If count > 0 Then
linecount += 1
Else
Console.WriteLine(" linecount=" & linecount)
End If
Next
Console.WriteLine("linecount= " & linecount)
Return linecount
End Function
Sub Main()
Dim lines() As String = IO.File.ReadAllLines("e:\ii.txt")
For Each line As String In lines
countlines(line)
Next
End Sub

I keep getting and error message 'Index was outside the bounds of the array'

I am trying to display information from a text file into a multiline textbox. I run the code but the system displays an error message 'Index was outside the bounds of the array'. There are no obvious error messages and I can't seem to manipulate the code to get rid of this problem. Take a look:
Public Class TeachCon
Dim layout As String
Dim Contacts(6) As Details
Structure Details
Dim Name As String
Dim Email As String
Dim RoomNum As String
Dim number1, number2 As Integer
End Structure
Sub LoadTeachContacts(ByRef Contacts() As Details)
Dim TextFile As String = "\\Sjcdom01\mstudent\LHeywood\documents\A2\Computing\Comp 4 - Smail\Project\Text Files\Teacher Contact List.txt"
Dim TextLine As String = ""
Dim ArrayCounter As Integer = 0
Dim objReader As New System.IO.StreamReader(TextFile)
'loop through text file and load all contacts
Do While objReader.Peek() <> -1
'read next line from file
TextLine = TextLine & objReader.ReadLine() & vbNewLine
'declare an array and use it to split line from file
Dim TempArray() As String = Split(TextLine, ",")
'transfer each array element into the appropriate part of the contacts stucture
Contacts(ArrayCounter).Name = TempArray(0)
*Contacts(ArrayCounter).Email = TempArray(1)*
Contacts(ArrayCounter).RoomNum = TempArray(2)
Contacts(ArrayCounter).number1 = TempArray(3)
Contacts(ArrayCounter).number2 = TempArray(4)
'empty string before reading next line from file
TextLine = ""
'increment array counter
ArrayCounter = ArrayCounter + 1
Loop
End Sub
Private Sub ButShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim ArrayCounter As Integer = 0
LoadTeachContacts(Contacts)
Do Until ArrayCounter = 3
layout = Contacts(ArrayCounter).Name & "," & Contacts(ArrayCounter).Email & "," & Contacts(ArrayCounter).RoomNum & "," & Contacts(ArrayCounter).number1 & "," & Contacts(ArrayCounter).number2
If ArrayCounter = 0 Then
TextBox7.Text = layout
End If
ArrayCounter += 1
Loop
End Sub
End Class
The text enclosed by the * is where the system says it is outside the bounds of the array.
Well, one of your lines probably splits into an array that is shorter than you expect, and hence the index does not exist. Check the length of the array before you get the value. Maybe something like this
If TempArray.Length > 0 Then Contacts(ArrayCounter).Name = TempArray(0)
If TempArray.Length > 1 Then Contacts(ArrayCounter).Email = TempArray(1)
If TempArray.Length > 2 Then Contacts(ArrayCounter).RoomNum = TempArray(2)
If TempArray.Length > 3 Then Contacts(ArrayCounter).number1 = TempArray(3)
If TempArray.Length > 4 Then Contacts(ArrayCounter).number2 = TempArray(4)
Don't know exactly what your TextFile contains in it. But inorder to handle the exception change the code as below
'declare an array and use it to split line from file
Dim TempArray() As String = Split(TextLine, ",")
'transfer each array element into the appropriate part of the contacts stucture
If TempArray.Length > 0 Then
Contacts(ArrayCounter).Name = TempArray(0)
*Contacts(ArrayCounter).Email = TempArray(1)*
Contacts(ArrayCounter).RoomNum = TempArray(2)
Contacts(ArrayCounter).number1 = TempArray(3)
Contacts(ArrayCounter).number2 = TempArray(4)
End If
'empty string before reading next line from file
TextLine = ""
It would be helpful if you could give the content of the file also:
"\Sjcdom01\mstudent\LHeywood\documents\A2\Computing\Comp 4 - Smail\Project\Text Files\Teacher Contact List.txt"
I think that you should check if the line is empty or not, because the item 0 will be available without error as a Null String, but the item 1 will throw 'Index was outside the bounds of the array' In LoadTeachContacts Sub
'read next line from file
If objReader.ReadLine().Trim = "" Then Continue Do
TextLine = TextLine & objReader.ReadLine() & vbNewLine

Resources