I have a text file like:
[edit] the number of line is unknown, it could be hundreds of lines.
How would I store them in a multidimensional array? I want my array to look like:
sample(0)(0) = "--------"
sample(0)(1) = "Line1"
..and so on
sample(1)(0) = "--------"
sample(1)(3) = "Sample 123"
..and so on
What I have done so far was to open the file and store in a 1-dimentional array:
logs = File.ReadAllLines("D:\LOGS.TXT")
I have tried creating an Array of string like:
Dim stringArray as String()()
stringArray = New String(varNumber0)(varNumber1)
But it returns and error.
You can use File.ReadLines/File.ReadAllLines to get the lines and a simple For Each-loop to fill a List(Of List(Of String)). Then you can use
list.Select(Function(l) l.ToArray()).ToArray()
to get the String()() (jagged array):
Dim lines = File.ReadLines("D:\LOGS.TXT")
Dim list As New List(Of List(Of String))
Dim current As List(Of String)
For Each line As String In lines.SkipWhile(Function(l) Not l.TrimStart.StartsWith("----------"))
If line.TrimStart.StartsWith("----------") Then
current = New List(Of String)
list.Add(current)
Else
current.Add(line)
End If
Next
Dim last = list.LastOrDefault()
If last IsNot Nothing Then
If Not current Is last AndAlso current.Any() Then
list.Add(current)
ElseIf Not last.Any() Then
list.Remove(last) ' last line was ("----------")'
End If
End If
Dim stringArray As String()() = list.Select(Function(l) l.ToArray()).ToArray()
If you want to include the --------- in the array at the first position:
For Each line As String In lines.SkipWhile(Function(l) Not l.TrimStart.StartsWith("----------"))
If line.TrimStart.StartsWith("----------") Then
current = New List(Of String)
current.Add(line)
list.Add(current)
Else
current.Add(line)
End If
Next
Try like this but you need to customize according to you
Dim mArray(10,10) As String
Dim i As Integer = 0
For I=0 to 10
For J=0 to 10
For Each line As String In System.IO.File.ReadAllLines("file.txt")
mArray(i,j) = cmdReader.Item(line)
Next
Next
Next
Use declaration like this (this is just a generic)
Dim dim1 As Integer = 0
Dim dim2 As Integer = 0
Dim strings(,) As String
Do
dim1 = NewDimensionNumberFromFile
dim2 = NewSecondDimensionNumberFromFile
ReDim Preserve strings(dim1, dim2)
strings(dim1, dim2) = ValueFromfile
Loop While (Not EOF()) 'this will determine
Related
I have code to ask a user for a series of codes that then creates a single-dimensional array like this:
Dim strDaysTimes As String
Dim arrDaysTimes() As String
strDaysTimes = InputBox("What days and times do you want to schedule meetings for? (write as 6c,7b)", "Enter Days and Times")
arrDaysTimes() = Split(strDaysTimes, ",")
The number of inputs is not defined but the format is. It could be "6c,7b" or "5a,6b,7b".
I want to convert this into a multi-dimensional array that would carry the values like this (one dimension has the number portion and the other has the letter portion):
5 a
6 b
7 b
I know that I need to use a nested For...Next statements to process multidimensional arrays, but I would appreciate any suggestions.
Use ReDim:
Public Function DivideArray()
Dim strDaysTimes As String
Dim arrDaysTimes() As String
Dim DaysTimes() As String
Dim Index As Integer
strDaysTimes = InputBox("What days and times do you want to schedule meetings for? (write as 6c,7b)", "Enter Days and Times")
arrDaysTimes() = Split(strDaysTimes, ",")
ReDim DaysTimes(UBound(arrDaysTimes) - LBound(arrDaysTimes) + 1, 0 To 1)
For Index = LBound(arrDaysTimes) To UBound(arrDaysTimes)
DaysTimes(Index, 0) = Left(LTrim(arrDaysTimes(Index)), 1)
DaysTimes(Index, 1) = Right(RTrim(arrDaysTimes(Index)), 1)
Next
For Index = LBound(arrDaysTimes) To UBound(arrDaysTimes)
Debug.Print DaysTimes(Index, 0), DaysTimes(Index, 1)
Next
End Function
Input example:
a7, b8, c9
Output:
a 7
b 8
c 9
Just for the sake of the art an alternative to #Gustav 's approach with the bonus that it returns token lengths greater than 1, too.
Furthermore it profits from the fact that the Val() function is able to return
a) the starting numeric value from an input string and
b) the closing string by a split via the above numeric value as delimiter.
Public Function tokenize(ByVal s As String)
Dim arr() As String
arr() = Split(Trim(s), ",")
Dim tmp() As String
ReDim tmp(0 To UBound(arr) - LBound(arr), 0 To 1)
Dim i As Long
For i = LBound(arr) To UBound(arr)
Dim num: num = Val(arr(i))
tmp(i, 0) = num
tmp(i, 1) = Split(arr(i), num)(1)
Next
tokenize = tmp
End Function
Example call
Sub testTokenize()
'0. Get input string (e.g. "6c,7b")
Dim strDaysTimes As String
strDaysTimes = InputBox( _
"What days and times do you want to schedule meetings for? (write as 6c,7b)", _
"Enter Days and Times", _
"6c,7b")
'1. Call help function
Dim results As Variant
results = tokenize(strDaysTimes) ' << function tokenize()
'2. Show results in VB Editor's immediate window
Dim i As Long
For i = LBound(results) To UBound(results)
Debug.Print results(i, 0), results(i, 1)
Next
End Sub
The following code will help you get there.
The GetDaysAndTimes function will return a Jagged array (i.e. an array of arrays). This means that to get the Day and Time of Item 3 you would use ArrayName(2)(0) and ArrayName(2)(1) where arrayname is the name of the array you are using (arrayDaysTimes?)
The function SplitAlphaNumString allows users to enter codes such as AB23.
Option Explicit
' This function takes the string returned by your input box
Public Function GetDaysAndTimes(ByRef ipString As String) As Variant
Dim myItems As Variant
myItems = VBA.Split(ipString, ",")
Dim myDayTimes As Variant
Dim myindex As Long
For myindex = LBound(myItems) To UBound(myItems)
myDayTimes(myindex) = SplitAlphaNumString(myItems(myindex))
Next
GetDaysAndTimes = myDayTimes
End Function
Public Function SplitAlphaNumString(ByVal ipString As String) As Variant
Dim myindex As Long
For myindex = 1 To VBA.Len(ipString)
If VBA.Asc(VBA.Mid(ipString, myindex, 1)) < 58 Then
Dim myAlphas As String
myAlphas = VBA.Mid(ipString, 1, myindex - 1)
Dim myNums As String
myNums = VBA.Mid(ipString, myindex)
SplitAlphaNumString = Array(myAlphas, myNums)
Exit Function
End If
Next
End Function
Sub Test()
Dim myArray As Variant
myArray = SplitAlphaNumString("D5")
Debug.Print myArray(0), myArray(1)
End Sub
I have the following code which loop through all the cells of the selected row. How to store all the values in an array?
Dim selectedCellCount As Integer = dgvData.GetCellCount(DataGridViewElementStates.Selected)
Dim RowVal As String
Dim i As Integer
For i = 0 To selectedCellCount - 1
RowVal = dgvData.SelectedCells(i).Value.ToString
Next i
End Sub
There is two method one with list another with array
1- List
Dim selectedCellCount As Integer = dgvData.GetCellCount(DataGridViewElementStates.Selected)
Dim RowVal As String
Dim i As Integer
Dim list As New List(Of string)
For i = 0 To selectedCellCount - 1
RowVal = dgvData.SelectedCells(i).Value.ToString
list.Add(RowVal)
Next i
End Sub
2- Array
Dim selectedCellCount As Integer = dgvData.GetCellCount(DataGridViewElementStates.Selected)
Dim RowVal As String
Dim i As Integer
Dim arrayOfData(selectedCellCount - 1) As String
For i = 0 To selectedCellCount - 1
RowVal = dgvData.SelectedCells(i).Value.ToString
arrayOfData(i) = RowVal
Next i
End Sub
Check out a List(of string). The list is easier to use than any other type of array. Here is a good explanation:
https://www.dotnetperls.com/list-vbnet
I need an array indexed with strings, like this:
Dim Array ("A") as integer' <-- I need an array like this
Dim StringArray() as string = {"A","B","C","A","A","B","D"}
For each Letter in StringArray
Array(Letter) += 1
next
Results I wanted but not worked:
Array(A) = 3
Array(B) = 2
Array(C) = 1
Array(D) = 1
I, also tried List's, not working:
Dim Array As New List(Of Object)
Dim StringArray() as string = {"A","B","C","A","A","B","D"}
For each Letter in StringArray
Array(Letter) += 1
next
Is there a way count strings this way in VB .Net?
You can use a Dictionary(Of TKey, TValue) where your letters are the keys, and the values will store your totals:
Dim dict = New Dictionary(Of Char, Integer)
dict.Add("A"c, 0)
dict.Add("B"c, 0)
dict.Add("C"c, 0)
dict.Add("D"c, 0)
Dim stringArray() As Char = {"A"c, "B"c, "C"c, "A"c, "A"c, "B"c, "D"c}
For Each letter In stringArray
dict.Item(letter) += 1
Next
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.
This question already has answers here:
Variable has been used before it has been assigned a value
(3 answers)
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I am trying to fill an array using a loop in VB. It basically read a .txt file and store all the line in an array. Im getting this error. "Array is used before it has been assigned values".
Dim fileEntries As String() = Directory.GetFiles(folderDIR, "*.txt")
Dim fileName As String
Dim fileReader As StreamReader
Dim strReadFile As String
Dim arrLines() As String
Dim i As Integer = 0
For Each fileName In fileEntries
fileReader = File.OpenText(fileName)
Do Until fileReader.Peek = -1
strReadFile = fileReader.ReadLine()
arrLines(i) = strReadFile
i += 1
Loop
Next
Is there any way I could do this, without pre-defining length of the array? I want the length of array to be number of lines in txt files. Hope i explained this well. Thank you in advance.
You can do something like this:
Dim fileEntries As String() = Directory.GetFiles(folderDIR, "*.txt")
Dim fileName As String
Dim fileReader As StreamReader
Dim strReadFile As String
Dim arrLines() As String = {} 'Added this
'Dim i As Integer = 0 'Removed this
For Each fileName In fileEntries
fileReader = File.OpenText(fileName)
Do Until fileReader.Peek = -1
strReadFile = fileReader.ReadLine()
If arrLines.Length = 0 Then ReDim arrLines(0 To 0) Else ReDim Preserve arrLines(0 To arrLines.Length)
arrLines(arrLines.Length - 1) = strReadFile
i += 1
Loop
Next
Or so...
There is quite a while, in vb6, I used ReDim to dynamically add a new entry in the array in the loop.
Inconvenient: slow down the process.
Better to count the occurrences needed from the file before creating the array.
Hope that helps.
you can declare arrlines as list:
Dim arrLines As New List(Of String)()
then you can convert to arrLines to array :
arrLines.ToArray()
try this:
Dim fileEntries As String() = Directory.GetFiles(folderDIR, "*.txt")
Dim fileName As String
Dim fileReader As StreamReader
Dim strReadFile As String
Dim arrLines As New List(Of String)()
Dim i As Integer = 0
For Each fileName In fileEntries
fileReader = File.OpenText(fileName)
Do Until fileReader.Peek = -1
strReadFile = fileReader.ReadLine()
arrLines.Add(strReadFile)
Loop
Next
arrLines.ToArray()