Visual Basic split function - visual-studio-2010

Ok so now I'm not getting an error but instead of everything being posted in the listbox it only contains the first line of text from the .txt file. This is the code I changed it too:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim inFile As IO.StreamReader
If IO.File.Exists("StudentList.txt") = True Then
inFile = IO.File.OpenText("StudentList.txt")
For index As Integer = 0 To inFile.Peek = -1
Dim splits = inFile.ReadLine.Split(","c)
Member(index).ID = splits(0)
Member(index).lastName = splits(1)
Member(index).firstName = splits(2)
Member(index).middleName = splits(3)
Member(index).grade = splits(4)
Member(index).period = splits(5)
ListBox1.Items.Add(Member(index).ID.PadLeft(10) & " " & Member(index).lastName & " " & Member(index).firstName)
Next
inFile.Close()
Else
MessageBox.Show("error", "error", MessageBoxButtons.OK)
End If
End Sub

The problem is that you're trying to assign a string array to a Member. That is, you have:
Member(index) = infile.ReadLine.Split(",", c);
You need to assign each field:
Dim splits = infile.ReadLine.Split(",", c);
Member(index).ID = splits(0);
Member(index).lastName = splits(1);
... etc.
Update after OP edit
I suspect the problem now is that your For loop is executing only once, or index isn't being incremented. I don't know where you came up with that wonky infile.Peek = -1 thing, but I suspect it doesn't work the way you think it does. Use something more conventional, like this.
Dim index As Integer = 0
For Each line As String In File.ReadLines("StudentList.txt")
Dim splits = line.Split(",", c)
Member(index).ID = splits(0)
' etc.
ListBox1.Add(...)
Index = Index + 1
Next

Related

Center align the data inside a datagrid in visual basic and remove the additional blank row generated at the end of the file

DataGridView1.Rows.Clear()
Try
Dim FileName As String = "C:\Users\xzqt\Desktop\test.csv"
Dim reader As New StreamReader(FileName, Encoding.Default)
Dim Line As String = ""
Dim colexpected As Integer = 3
Dim a As Integer = 0
Do
Line = reader.ReadLine
If Line Is Nothing Then Exit Do
Dim words() As String = Line.Split(",")
DataGridView1.Rows.Add()
For x As Integer = 0 To 2
DataGridView1.Rows(a).Cells(x).Value = words(x)
Next
a = a + 1
Loop
reader.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Output of the data:
Is there a way how I can center align the data from datagrid in visual basic and remove the blank row at the end of it. Attached is the screenshot for further details.Thank you.

Count Items in file using VB

Kind of new to VBS. I'm trying to count the fields in the file and have this code.
Col()
Function Col()
Const FSpec = "C:\test.txt"
Const del = ","
dim fs : Set fs = CreateObject("Scripting.FileSystemObject")
dim f : Set f = fs.OpenTextFile(FSpec, 1)
Dim L, C
Do Until f.AtEndOfStream
L = f.ReadLine()
C = UBound(Split(L, del))
C = C +1
WScript.Echo "Items:", C
Loop
f.Close
End Function
It works however, I don't want to count the delim inside " ".
Here's file content:
1,"2,999",3
So basically, I'm getting 4 items for now but I wanted to get 3. Kind of stuck here.
For an example of my second suggestion, a very simple example could be something like this. Not saying it is perfect, but it illustrates the idea:
Dim WeAreInsideQuotes 'global flag
Function RemoveQuotedCommas(ByVal line)
Dim i
Dim result
Dim current
For i = 1 To Len(line)
current = Mid(line, i, 1) 'examine character
'check if we encountered a quote
If current = Chr(34) Then
WeAreInsideQuotes = Not WeAreInsideQuotes 'toggle flag
End If
'process the character
If Not (current = Chr(44) And WeAreInsideQuotes) Then 'skip if comma and insode quotes
result = result & current
End If
Next
RemoveQuotedCommas = result
End Function

How to collect a certain string anywhere in an item in a ListBox?

I have been trying to find out how to collect a string anywhere in a Listbox, I use Visual Basic 2010 and this is more of an request, but there is code I found so you fix the code I found or tell me me an another code to use.
I have tried using ListBoxName.Items.Contains but that did not work, I tried a lot of methods and it would be hard to say all of then at once.
' Split string based on space
Dim textsrtring As String = ListBox.Text
Dim words As String() = textsrtring.Split(New Char() {" "c})
Dim found As Boolean = False
' Use For Each loop over words
Dim word As String
For Each word In words
If ListBox.Items.Contains(word) Then
found = True
Exit For
End If
Next
MessageBox.Show(found)
They were no errors, the message box that appeared kept on telling me false and there is no string when I clearly put it in, no error messages.
You'll need an inner loop to see if each word is contained in your main listbox entry using String.Contains():
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim searchFor As String = TextBox1.Text.Trim
If searchFor.Length > 0 Then
Dim words As String() = searchFor.Split(New Char() {" "c})
Dim found As Boolean = False
Dim foundAt As Integer
' Use For Each loop over words
Dim word As String
For Each word In words
For i As Integer = 0 To ListBox.Items.Count - 1
If ListBox.Items(i).ToString.Contains(word) Then
found = True
foundAt = i
Exit For
End If
Next
If found Then
Exit For
End If
Next
If found Then
ListBox.SelectedIndex = foundAt
Label1.Text = "Search string found."
Else
ListBox.SelectedIndex = -1
Label1.Text = "Search string NOT found."
End If
Else
ListBox.SelectedIndex = -1
Label1.Text = "No search string."
End If
End Sub

VBScript: Resort String and group with new Split Item

'I Have the below String.. that splited with "#"
myStr = "78,6$25,01|25,02|25,03|25,04#74,5$15,01|15,02|15,03|15,04#70,1$25,06|25,07|25,08|25,09#77,3$25,07|25,08|25,09|25,10#78,2$10,05|10,06|10,07|10,08"
'And I want resort to this New String with New Grouping...
'i should group splited string with first value after dollar($) chrachter
But i dont know how should I Sorting and Grouping to new desired result:
myStrDesired = "78,2$10,05|10,06|10,07|10,08#74,5$15,01|15,02|15,03|15,04#78,6$25,01|25,02|25,03|25,04#70,1$25,06|25,07|25,08|25,09#77,3$25,07|25,08|25,09|25,10"
My Script:
Function GroupArrays()
myStr = "78,6$25,01|25,02|25,03|25,04#74,5$15,01|15,02|15,03|15,04#70,1$25,06|25,07|25,08|25,09#77,3$25,07|25,08|25,09|25,10#78,2$10,05|10,06|10,07|10,08"
'And I want resort to this New String with New Grouping...
'i should group splited string with first value after dollar($) chrachter
myStrDesired = "78,2$10,05|10,06|10,07|10,08#74,5$15,01|15,02|15,03|15,04#78,6$25,01|25,02|25,03|25,04#70,1$25,06|25,07|25,08|25,09#77,3$25,07|25,08|25,09|25,10"
arrMyStr = Split(myStr,"#")
arrMyStrDesired = ""
for i = 0 to UBound(arrMyStr)
' find group id from each string
groupVal = Split(Split(arrMyStr(i),"$")(1),",")(0)
' put the same groups together and split them by "#" And finally the isolation of other disciplines with "#"
arrMyStrDesired = arrMyStrDesired & arrMyStr(i)
next
GroupArrays = arrMyStrDesired
End Function
New Description:*
Split the main String by "#".
In the each parts splited... see the first value after "$" and name to "groupId". (it is Important parameter for Grouping and sorting)
All of each parts has same groupId should be placed side by side and Joined by "#".
After above Steps... we should Join All New strings with other groupId by "#".... same as ... (00$01,05#01,06#...#02,07#03,4.....)
The following should work on any Windows machine with the Dot Net runtime. If for some reason you don't have that -- would need a custom sort:
myStr = "78,6$25,01|25,02|25,03|25,04#74,5$15,01|15,02|15,03|15,04#70,1$25,06|25,07|25,08|25,09#77,3$25,07|25,08|25,09|25,10#78,2$10,05|10,06|10,07|10,08"
myDesiredStr = "78,2$10,05|10,06|10,07|10,08#74,5$15,01|15,02|15,03|15,04#78,6$25,01|25,02|25,03|25,04#70,1$25,06|25,07|25,08|25,09#77,3$25,07|25,08|25,09|25,10"
Function GroupVal(group)
A = Split(group,"$")
B = Split(A(1),",")
GroupVal = CInt(B(0))
End Function
Function ReSort(str)
Set D = CreateObject("Scripting.Dictionary")
Set keyList = CreateObject("System.Collections.ArrayList")
groups = Split(str,"#")
For i = 0 to UBound(groups)
group = groups(i)
v = GroupVal(group)
If D.Exists(v) Then
D.Item(v) = D.Item(v) & "#" & group
Else
D.Add v,group
keyList.Add v
End If
Next
keyList.Sort()
newGroups = Array()
ReDim newGroups(Ubound(groups))
i = -1
For Each v In keyList
i = i + 1
newGroups(i) = D.item(v)
Next
ReDim Preserve newGroups(i)
Resort = Join(newGroups,"#")
End Function
MsgBox myDesiredStr = Resort(myStr)
The msgbox pops up True

Excel copy/sort data while counting/removing duplicates

Ok so I've searched and searched and can't quite find what I'm looking for.
I have a workbook and what I'm basically trying to do is take the entries from certain ranges (Sheet1 - E4:E12, E14:E20, I4:I7, I9:I12, I14:I17, & I19:I21) and put them in a separate list on Sheet2. I then want the new list on Sheet2 to be sorted by how many times an entry appeared on Sheet1 as well as display the amount.
example http://demonik.doomdns.com/images/excel.png
Obviously as can be seen by the ranges I listed above, this sample is much smaller lol, was just having trouble trying to figure out how to describe everything and figured an image would help.
Basically I am trying to use VBA (the update would be initialized by hitting a button) to copy data from Sheet1 and put all the ranges into one list in Sheet2 that is sorted by how many times it appeared on Sheet1, and then alphabetically.
If a better discription is needed just comment and let me know, I've always been horrible at trying to describe stuff like this lol.
Thanks in advance!
Another detail: I cant have it search for specific things as the data in the ranges on Sheet1 may change. Everything must be dynamic.
I started out with this data
and used the following code to read it into an array, sort the array, and count the duplicate values, then output the result to sheet2
Sub Example()
Dim vCell As Range
Dim vRng() As Variant
Dim i As Integer
ReDim vRng(0 To 0) As Variant
Sheets("Sheet2").Cells.Delete
Sheets("Sheet1").Select
For Each vCell In ActiveSheet.UsedRange
If vCell.Value <> "" Then
ReDim Preserve vRng(0 To i) As Variant
vRng(i) = vCell.Value
i = i + 1
End If
Next
vRng = CountDuplicates(vRng)
Sheets("Sheet2").Select
Range(Cells(1, 1), Cells(UBound(vRng), UBound(vRng, 2))) = vRng
Rows(1).Insert
Range("A1:B1") = Array("Entry", "Times Entered")
ActiveSheet.UsedRange.Sort Range("B1"), xlDescending
End Sub
Function CountDuplicates(List() As Variant) As Variant()
Dim CurVal As String
Dim NxtVal As String
Dim DupCnt As Integer
Dim Result() As Variant
Dim i As Integer
Dim x As Integer
ReDim Result(1 To 2, 0 To 0) As Variant
List = SortAZ(List)
For i = 0 To UBound(List)
CurVal = List(i)
If i = UBound(List) Then
NxtVal = ""
Else
NxtVal = List(i + 1)
End If
If CurVal = NxtVal Then
DupCnt = DupCnt + 1
Else
DupCnt = DupCnt + 1
ReDim Preserve Result(1 To 2, 0 To x) As Variant
Result(1, x) = CurVal
Result(2, x) = DupCnt
x = x + 1
DupCnt = 0
End If
Next
Result = WorksheetFunction.Transpose(Result)
CountDuplicates = Result
End Function
Function SortAZ(MyArray() As Variant) As Variant()
Dim First As Integer
Dim Last As Integer
Dim i As Integer
Dim x As Integer
Dim Temp As String
First = LBound(MyArray)
Last = UBound(MyArray)
For i = First To Last - 1
For x = i + 1 To Last
If MyArray(i) > MyArray(x) Then
Temp = MyArray(x)
MyArray(x) = MyArray(i)
MyArray(i) = Temp
End If
Next
Next
SortAZ = MyArray
End Function
End Result:
Here is a possible solution that I have started for you. What you are asking to be done gets rather complicated. Here is what I have so far:
Option Explicit
Sub test()
Dim items() As String
Dim itemCount() As String
Dim currCell As Range
Dim currString As String
Dim inArr As Boolean
Dim arrLength As Integer
Dim iterator As Integer
Dim x As Integer
Dim fullRange As Range
Set fullRange = Range("E1:E15")
iterator = 0
For Each cell In fullRange 'cycle through the range that has the values
inArr = False
For Each currString In items 'cycle through all values in array, if
'values is found in array, then inArr is set to true
If currCell.Value = currString Then 'if the value in the cell we
'are currently checking is in the array, then set inArr to true
inArr = True
End If
Next
If inArr = False Then 'if we did not find the value in the array
arrLength = arrLength + 1
ReDim Preserve items(arrLength) 'resize the array to fit the new values
items(iterator) = currCell.Value 'add the value to the array
iterator = iterator + 1
End If
Next
'This where it gets tricky. Now that you have all unique values in the array,
'you will need to count how many times each value is in the range.
'You can either make another array to hold those values or you can
'put those counts on the sheet somewhere to store them and access them later.
'This is tough stuff! It is not easy what you need to be done.
For x = 1 To UBound(items)
Next
End Sub
All that this does so far is get unique values into the array so that you can count how many times each one is in the range.

Resources