Getting the first 6 strings in a string array in VB - arrays

I have a String array which gets all the files from a directory. Dim files() as string = IO.Directory.GetFiles(xxx)
These files are being added as nodes on a TreeView. The issues I am having is, when there are 300 files in the array. I loop through and get each file and add all 300 to the Treeview. But I want to only get the first 100 files from the array and only add those. I feel like this should be pretty simple but trying to figure out how to get the first 100 strings(files) from the array is slipping my mind. Any help would be greatly appreciated.

Opt 1) Use take()
Dim files() as string = IO.Directory.GetFiles("C:\Temp").Take(6)
Opt 2) Use a for loop
Dim files() as string = IO.Directory.GetFiles("C:\Temp")
For i as Integer = 0 to 5
TreeView1.Nodes.Add(files(i))
Next

Related

Array of 600+ Strings in excel VBA

I am doing a loop for each string in an array such that
filename = Array(file1,file2.....file600)
However VBA gets a compile error that is due to the array taking up 8 lines. As far as I am aware it only allows 1 line
(error says expected list or separator)
I am new to VBA sorry
You can escape new lines in VBA with _.
so your solution might look like
filename = Array("file1", _
"file2", _
"file3")
See How to break long string to multiple lines and If Statement With Multiple Lines
If you have 100's of names, however, you might be better off storing them in a worksheet and reading them in, rather than hard-coding them.
Should you strings in the array be actually "buildable" following a pattern (like per your examples: "file1", "file2", ...,"file600") then you could have a Function define them for you, like follows:
Function GetFileNames(nFiles As Long) As String()
Dim iFile As Long
ReDim filenames(1 To nFiles) As String
For iFile = 1 To nFiles
filenames(iFile) = "file" & iFile
Next
GetFileNames = filenames
End Function
which you'd call in your "main" code as follows
Sub main()
Dim filenames() As String
filenames = GetFileNames(600) '<--| this way'filenames' array gets filled with 600 hundred values like "file1", "file2" and so on
End Sub
The amount of code that can be loaded into a form, class, or standard module is limited to 65,534 lines. A single line of code can consist of up to 1023 bytes. Up to 256 blank spaces can precede the actual text on a single line, and no more than twenty-four line-continuation characters ( _) can be included in a single logical line.
From VB6's Help.
when programming, you don't build an array this big mannually, never.
either you store each multiline-string inside a Cell, and at the end you buid the array like this :
option Explicit
Sub ArrayBuild ()
Dim Filenames() 'as variant , and yes i presume when using multi files, the variable name should have an "s"
With Thisworkbook.sheets("temp") 'or other name of sheet
Max = .cells(.rows.count,1).end(xlup).row '=max number of rows in column 1
Filenames = .range( .cells(1,1) , .cells(Max,1)).value2 ' this example uses a one column range from a1 to a[max] , but you could also use a multi column by changing the second .cells to `.cells(Max, ColMax)`
end with
'do stuff
erase Filenames 'free memory
End Sub
An other way is to build an array like you build a house by adding one brick at a time, like this :
Dim Filenames() as string 'this time you can declare as string, but not in the previous example
Dim i& 'counter
For i=1 to Max 'same max as in previous example, adapt code plz...
redim Preserve Filenames (1 to ubound(filenames)+1) 'this is an example for unknown size array wich grows, but in your case you know the size (here Max, so you could declare it `Dim Filenames (1 to Max)` from the start, just wanted to show every option here.
Filenames(i) = Cells (i,1).value2 'for example, but can be anything else. Also i'm beeing lazy and did not reference the cell to its sheet, wich i'd never do in actual coding...
next i
EDIT i did re-read your Question, and it is even easier (basically because you ommited the bracets in your post and corrected it as comment...), use
user3598756 's code plz. I thought File1 is a variable, when it should be written as "File1" .
EDIT 2 why bother build and array where Filename(x)="Filex" anyway? you know the result beforehand

VBA Associative Arrays (How to Index)

I'm a newbie to VBA so please forgive my lack of experience.
Im using excel VBA and trying to figure out how to index an array. I'm importing a CSV and using the split function. I need to access each individual items of the items split into the array(s). The best way to explain what I need is an example like this from Actionscript:
var a:Array = [];
a[1] = "Hello";
a[2] = "World";
(Except that what I have is a dynamic array created by the SPLIT function)
Where I could access "Hello" with the var a[1]
Here is what I have so far:
Sub getTxtfile()
FilePath = Application.GetOpenFilename _
(Title:="Please choose a file to open", _
FileFilter:="CSV Files *.csv* (*.csv*),")
Open FilePath For Input As #1
row_number = 0
Do Until EOF(1)
Line Input #1, LineFromFile
LineItems = Split(LineFromFile, ",")
'ActiveCell.Offset(row_number, 0).Value = LineItems(1)
'ActiveCell.Offset(row_number, 1).Value = LineItems(0)
row_number = row_number + 1
'Debug.Print LineItems(0) & ": " & LineItems(1)
Loop
Close #1
End Sub
I now have 2 arrays (LineItems(0) & LineItems(1)) but how do I index what is inside of them at this point?
Thanks for any and all help, it is greatly appreciated.
Mike
The CSV I'm using is formatted to use with other applications SolidWorks, python, etc.) besides Excel. I need to access only certain elements within the array to populate certain cells. As it is...I can pull the entire array into columns but I don't want to do that, just the ones I need. Here is a sample of the CSV:
0,.200
p,1.0709
q,1.167
r,1.177
s,1.216
t,1.570
u,1.5843
v,1.6883
w,1.9079
e,.2645
What I want to do is reference the letter in the first element and have the second element inserted in a certain cell: Reference "t" through an index and have "1.570" inserted.
The elements in my arrays are LineItems(0) and LineItems(1). So ideally I'm looking to reference each indexed item in an element as LineItems(1)(a) / LineItems(1-a) or something similar to that.
I think the commented-out lines in your code should actually work, at least as far as array access is concerned. (However, I may not fully understand what you are trying to accomplish. Would you please edit your question to clarify?) I do recommend adding
Option Explicit
Option Base 0
at the top of your file, and
Dim LineItems as Variant
before the Split call. That way the compiler will help you find errors.
However, If what you really want is to open a CSV, please allow me to suggest:
Dim wb as Workbook
Workbooks.OpenText Filename:="<filename>", DataType:=xlDelimited, Comma:=True
Set wb = Workbooks(Workbooks.Count)
which will give you a new workbook wb with the CSV parsed and ready to be accessed just like any other worksheet (docs on MSDN).
You can have associative arrays in VBA with Scripting.Dictionary object or the .NET System.Collections.HashTable, but that seems a bit overkill.
You can use Jagged Arrays (Arrays of Arrays) like this:
Line = "0,.200 p,1.0709 q,1.167 r,1.177 s,1.216 t,1.570 u,1.5843 v,1.6883 w,1.9079 e,.2645"
LineItems = Split(Line, ",")
Dim LineSubItems() ' has to be Variant or Variant() array
ReDim LineSubItems(0 To UBound(LineItems))
For i = 0 To UBound(LineItems)
LineSubItems(i) = Split(LineItems(i), " ")
Next
Debug.Print LineSubItems(1)(1) ' "p"

how to sort an array of string containing numbers, numerically

So as the title already suggests I simply want to know if it is possible to sort elements that are in a string array via the numbers that are also contained within those strings.
In my program I have been able to read the contents of a file which are laid out like this:
Adele got 2,Jack got 8
I have then been able to split this file via the comma into a string array called names:
Dim fileReader As System.IO.StreamReader
Dim line As String
fileReader = My.Computer.FileSystem.OpenTextFileReader(ClassA)
line = fileReader.ReadLine
names = line.Split(",")
For Each element As String In names
Array.Sort(names)
Console.WriteLine(element)
Next
I was also able to sort the file alphabetically giving an output of:
Adele got 2
Jack got 8
However what I want to know is whether it is or isn't possible to sort these strings based on the number so the output would look like:
Jack got 8
Adele got 2
I also considered using regex to extract the numbers, parse them as integer, save them to a variable and then add them to an array and compare the arrays but their has to be a simpler way D:
Any help is much appreciated guys :)
Linq to the rescue. I added to the data to be sure it would handle 2 digit numerals and because 2 elements is a feeble test:
Dim phrases As String() = {"Adele got 2", "Zalgo got 9", "Jack got 8", "Ziggy got 11"}
phrases = phrases.OrderByDescending(Function(q) Int32.Parse(q.Split(" ").Last)).ToArray()
For Each s In phrases
Console.WriteLine(s)
Next
Result:
Ziggy got 11
Zalgo got 9
Adele got 8
Jack got 2
Yes, it's possible. Add a comparer function, and then sort using it. This is the comparer:
Private Shared Function WhoGotComparer(ByVal x As String, ByVal y As String) As Integer
Dim parseX() As String = Split(x, " got ")
Dim parseY() As String = Split(y, " got ")
If parseX.Length <> 2 Or parseY.Length <> 2 Then Return 0
Return CInt(parseY(1)).CompareTo(CInt(parseX(1))) 'Performs an integer comparison.
End Function
Add it to your code. You can make use of it like this:
names.Sort(AddressOf WhoGotComparer)
This should result in the array being sorted in descending order. I think that is what you wanted based on the example. If you want to change the order to ascending you can reverse the roles of they x and y parameters in the comparer function, or you can negate the results of the Compare.

Index was outside the bounds of the String array

I have this test code in VB:
Dim st As New ScheduledTasks("\\webserver")
Dim tasknames() As String = st.GetTaskNames
ListBox1.Items.Add(tasknames(1))
st.Dispose()
When i run it i get an error on line:
ListBox1.Items.Add(tasknames(1))
Index was outside the bounds of the array.
Does anyone have any suggestions what im doing wrong?
tasknames must contain at least 2 items for your code to work. (Note that arrays are 0-based, so you start counting at 0)
You have to check whether it really contains that amount:
If tasknames.Length >= 2
Then
ListBox1.Items.Add(tasknames(1))
End If

How to iterate an array of a dynamic size in a loop

I am using VB.NET.
I would like have an array called A1 and I will perform for loop inside that array.
In the middle of the for loop, I need to remove an item from that A1 array.
I am aware that if I remove that object from A1 array, the program will crash (out of bounds error message).
Which array variable in VB.NET would allow me to perform the task above?
Code sample is most welcomed!
Thank you.
The easiest way would be to use a list instead of an array (or convert the array you have to a List(of T).
The trick then is to move from the end of the list to the front instead of the other way around.
For example:
Sub Main()
Dim RndGenerator as New Random
Dim a As New List(Of Double)
For i = 0 To 99
a.Add(RndGenerator.NextDouble() * 10) 'Populate the list
Next
For i = a.Count - 1 To 0 Step -1 'This loop performs the deletion.
If a(i) > 5 Then a.RemoveAt(i)
Next
Console.ReadKey() 'Or debugger.Break to look at the result
End Sub
This will populate a list with random numbers from 0 to 10. It then removes all numbers >5 from the list.
Edit:
Good point from Steven Doggart on not using VB6 Relics. Edited the code to use the System.Random class instead.

Resources