Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using collection in VB 1

Status
Not open for further replies.

VisualBasicHelp

Programmer
Sep 7, 2005
74
GB

Our team leader told me to use collection in VB for reading a file, so that no need to read again and again from file and We can store the file, line by line in collection.

But I don't know anything about collection. Can anybody help me to use collection.

Thanks
 
If you are really going down this particular design route for handling files, tell your team leader that you'd be better off using a Dictionary rather than a Collection (as a Dictionary is faster and more flexible)
 
Collection are really cool when you need to perform lookups on the data.

Unfortunately, collection are not the most appropriate object to use in your situation. In my experience, collections are slow. very slow.

I would recommend that you use an array instead. Reading from files is relatively fast. Splitting a file in to an array is also relatively fast. Looping through an array is fast. Arrays are cool!

Essentially, you will have an array that stores the data line by line instead of a collection.

To get you started, lookup FileSystemObject to read from your data file. There are several method of getting the data out of a file. I prefer the .ReadAll method. Esentially, you end up with a string that contains the entire contents of the file. Then, use split to seperate the lines in to your array.

Here's some sample code to get you started.

Code:
Option Explicit

Public MyArray() As String

Private Sub btnLoopThroughFile_Click()
    
    Dim i As Long
    
    For i = LBound(MyArray) To UBound(MyArray)
        Debug.Print MyArray(i)
    Next
    
End Sub

Private Sub Command1_Click()
    
    Dim FSO As Scripting.FileSystemObject
    Dim strFileContents As String
    
    Set FSO = CreateObject("Scripting.FileSystemObject")
    strFileContents = FSO.OpenTextFile("C:\Folder\File.ext", ForReading).ReadAll
    Set FSO = Nothing
    
    MyArray = Split(strFileContents, vbCrLf)
    
End Sub

Or the evil way of loading the file. [wink]

Code:
    MyArray = Split(CreateObject("Scripting.FileSystemObject").OpenTextFile("C:\Folder\File.ext", ForReading).ReadAll, vbCrLf)

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Thanks a lot for a good and valuable suggestion. So I think I will be more comfortable with array than collection. Since I have been using arrays in C,C++ etc.
Thanks again.
 
As our leader is adamant in using collection, can you please provide me some help in collection.
 
OK.It 's a round peg in a square hole, but apparently it's not your decision to make (or mine). Been there, done that.

Here is some sample code to get you started.

Code:
Option Explicit

Dim colFileData as Collection

Private Sub Command1_Click()
    
    Dim i As Long
    
    Call LoadFileToCollection(colFileData, "C:\Test.txt")
    
    For i = 1 To colFileData.Count
        Debug.Print colFileData.Item(i)
    Next
    
End Sub

Public Sub LoadFileToCollection(ByRef tmpCollection As Collection, ByVal FileName As String)
    
    Dim FSO As Scripting.FileSystemObject
    Dim arTemp() As String
    Dim i As Long
    Dim strData As String
    
    Set FSO = CreateObject("Scripting.FileSystemObject")
    strData = FSO.OpenTextFile(FileName, ForReading).ReadAll
    Set FSO = Nothing
    
    arTemp = Split(strData, vbCrLf)
    Set tmpCollection = New Collection
    For i = LBound(arTemp) To UBound(arTemp)
        Call tmpCollection.Add(arTemp(i))
    Next
    
    Erase arTemp
    
End Sub

Of course, you will notice that I am still using arrays to fill up the collection. You can further slow this down by eliminating arrays all together. Here's how.

Code:
Public Sub LoadFileToCollection(ByRef tmpCollection As Collection, ByVal FileName As String)
    
    Dim FSO As Scripting.FileSystemObject
    Dim oStream As Scripting.TextStream
    
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set oStream = FSO.OpenTextFile(FileName, ForReading)
    Set FSO = Nothing
        
    Set tmpCollection = New Collection
    
    While Not oStream.AtEndOfStream
        Call tmpCollection.Add(oStream.ReadLine)
    Wend
    
    
End Sub

Of course, it's true that if your data files are small, you will not notice a difference in performance.

-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
But you stopped being evil George ...

Here's my version. As I said before, if the leader insists on this sort object in the solution I'd advise using a Dictionary instead of a Collection - it does almost everything that a Collection does, but is more flexible, dramatically faster, and has additional features (e.g if you wish you can treat the items it contains as a genuine array)
Code:
[blue]Option Explicit
Private myCollection As Dictionary

Private Sub Command1_Click()
    Dim lp As Long
    
    LoadFileToCollection "C:\readme.txt"
    
    ' Look, here it is as an array
    For lp = LBound(myCollection.Items) To UBound(myCollection.Items)
        Debug.Print myCollection.Items(lp)
    Next

    ' Here it is in the more classical collection methodology
    For lp = 1 To myCollection.Count
        Debug.Print myCollection.Item(lp)
    Next

End Sub

Public Sub LoadFileToCollection(strFilename As String)
    Dim wombat As Variant
    Dim myKey As Long
    
    Set myCollection = New Dictionary
    For Each wombat In Split(CreateObject("Scripting.FileSystemObject").OpenTextFile(strFilename, ForReading).ReadAll, vbCrLf)
        myCollection.Add myKey, wombat
        myKey = myKey + 1 ' Just generating  unique key
    Next
End Sub[/blue]

 
<Private myCollection As Dictionary
Now there's a nice touch....simply evil.
 
These last couple of threads remind me of the Simpson's episode where Bart wants to get into Scouting so he can play with knives. He's given a knife safety book named (or containing) a phrase like "Don't Do What Donny Don't Does.
 
I am trying the code of FileSystemObject in my VB 6. But its giving me error that "user-defined type not defined".

Can you please tell me, what else I should do for it. Do I need to include anything.

Thanks
 
You need to make sure that it is referenced in your project.

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
I have added the reference of system.dll, will that be fine, or do I need to add any other reference
 
Instead of dynamically reading a file, you can also prompt the user to select the file to read:

cdlOpen.Filter = "ThirdParty (*.txt)|*.txt|ThirdParty (*.csv)|*.csv"
cdlOpen.filename = ""
cdlOpen.ShowOpen
If cdlOpen.filename <> "" Then
Open cdlOpen.filename For Input As #1 ' open selected file (txt) for reading.
Do While Not EOF(1) ' read ea. line in the txt file.
' read each line in the file and load into your collection.
Loop

HTH


Many Thanks!

AMACycle

American Motorcyclist Association
 
I don't remember the name of the DLL. That sounds right. Will it compile and run? If so, then that was it.

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
The code won't compile only.
It's not understanding the declaration

dim FSO as FileSystemObject


I am trying to use the FileSystemObject, as I can use all the functions which it gives me.
 
I got it, I had to add one more reference of "Microsoft scripting runtime". And now its working fine.

Thanks a lot
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top