I want to make a VB6 executable that can handle a text file (or more) that have the following format.
X1 field | Y1 field | Z1 field \n
X2 field | Y2 field | Z2 field \n
....\n
....\n
Xn field | Yn field | Zn field.
It look's like a table from db or csv file and I would like to make a VB6 program that can search, edit and add all these fields. Is there any library or framework in VB6 to help me?
A disconnected database.
Sub Randomise
Randomize
Set rs = CreateObject("ADODB.Recordset")
With rs
.Fields.Append "RandomNumber", 4
.Fields.Append "Txt", 201, 5000
.Open
Do Until Inp.AtEndOfStream
.AddNew
.Fields("RandomNumber").value = Rnd() * 10000
.Fields("Txt").value = Inp.readline
.UpDate
Loop
.Sort = "RandomNumber"
Do While not .EOF
Outp.writeline .Fields("Txt").Value
.MoveNext
Loop
End With
End Sub
It all depends on what you want to do with the data but you can use the following steps:
Read in the file, either per line or the complete file at once
Substract the data in the correct format
write the data to your favorite database/control
For example, to read in the whole file at once, and show its fields into a MSFlexGrid you can do the following:
'1 form with:
' 1 MSFlexFrid control: name=MSFlexGrid1
' 1 Command button: name=Command1
Option Explicit
Private Sub Command1_Click()
Dim lngLine As Long, lngField As Long
Dim intFile As Integer
Dim strFile As String
Dim strData As String
Dim strLine() As String, strField() As String
'read the file
strFile = "c:\temp\file.txt"
intFile = FreeFile
Open strFile For Input As #intFile
strData = Input(LOF(intFile), #intFile)
Close #intFile
'split the file in separate lines
strLine = Split(strData, "\n")
'fill the grid with the data
With MSFlexGrid1
.Rows = UBound(strLine) + 1
For lngLine = 0 To UBound(strLine)
'put all fields from 1 line on 1 row in the grid
strField = Split(strLine(lngLine), "|")
If UBound(strField) > .Cols - 1 Then
.Cols = UBound(strField) + 1
End If
For lngField = 0 To UBound(strField)
.TextMatrix(lngLine, lngField) = strField(lngField)
Next lngField
Next lngLine
End With 'MSFlexGrid1
End Sub
Private Sub Form_Resize()
Dim sngWidth As Single, sngHeight As Single
Dim sngGrdHeight As Single
Dim sngCmdHeight As Single
sngWidth = ScaleWidth
sngHeight = ScaleHeight
sngCmdHeight = 315
sngGrdHeight = sngHeight - sngCmdHeight
MSFlexGrid1.Move 0, 0, sngWidth, sngGrdHeight
Command1.Move 0, sngGrdHeight, sngWidth, sngCmdHeight
End Sub
Related
Scenario: I am reading through folders and subfolders of a directory, if the found file is an ".xls" it opens. I then run another condition that, if true, will try to pass some values to the array.
Objective: I am defining my array without dimensions, because I don't know how many files will feed into it. For each file that fulfills the conditions, I am trying to get 3 values (name, path, date) and add to the array. Each file would be added to a new row of the array.
Ex. of array:
If 3 files fulfill the condition...
name1 path1 date1
name2 path2 date2
name3 path3 date3
Issue: when I run, I get a subscript out of range error when I try to pass the values to the array. How can I fix that?
Code1: This starts the loop through folders
Public Sub getInputFileInfo()
Dim FileSystem As Object
Dim HostFolder As String
' User selects where to search for files:
HostFolder = GetFolder()
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
End Sub
Code2: This gets the data:
Public Sub DoFolder(Folder)
Dim strFilename As String, filePath As String
Dim dateC As Date
Dim oFS As Object
Dim outputarray() As Variant
Dim ii As Long, lRow As Long, lCol As Long, lRow2 As Long
Dim w2, w As Workbook
Set w = ThisWorkbook
ii = 1
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next SubFolder
Dim File
For Each File In Folder.Files
Set oFS = CreateObject("Scripting.FileSystemObject")
'Set w2 = File
filePath = File.Path
strFilename = File.Name
dateC = File.dateCreated
If InStr(LCase(File.Path), LCase("xls")) <> 0 Then
Set w2 = Workbooks.Open(filePath)
For lRow2 = 1 To w2.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
If w2.Sheets(1).Range("A" & lRow2).Value = "Test Name" Then
outputarray(0, ii) = strFilename ' THE ERROR STARTS HERE
outputarray(1, ii) = filePath
outputarray(2, ii) = dateC
ii = ii + 1
End If
Next lRow2
w2.Close False
End If
Set oFS = Nothing
Next File
For lRow = 1 To UBound(outputarray, 1)
For lCol = 1 To UBound(outputarray, 2)
w.Sheets("ControlSheet").Cells(lRow, lCol).Value = outputarray(lRow, lCol).Value
Next lCol
Next lRow
End Sub
I would use a dictionary and a "class" like in the following example.
The class fInfo looks like that
Option Explicit
Public fileName As String
Public filepath As String
Public fileDateCreated As Date
Then you could test it like that
Sub AnExample()
Dim dict As New Scripting.Dictionary
Dim fInfo As fileInfo
Dim filepath As String
Dim strFilename As String
Dim dateC As Date
Dim i As Long
For i = 1 To 2
filepath = "Path\" & i
strFilename = "Name" & i
dateC = Now + 1
Set fInfo = New fileInfo
With fInfo
.filepath = filepath
.fileName = strFilename
.fileDateCreated = dateC
End With
dict.Add i, fInfo
Next i
For i = 1 To dict.Count
With dict.Item(i)
Debug.Print .filepath, .fileName, .fileDateCreated
End With
Next i
End Sub
In your code maybe like that
For lRow2 = 1 To w2.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
If w2.Sheets(1).Range("A" & lRow2).Value = "Test Name" Then
Set fInfo = New fileInfo
With fInfo
.filepath = filepath
.fileName = strFilename
.fileDateCreated = dateC
End With
dict.Add ii, fInfo
' outputarray(0, ii) = strFilename ' THE ERROR STARTS HERE
' outputarray(1, ii) = filepath
' outputarray(2, ii) = dateC
' ii = ii + 1
End If
Next lRow2
try with these steps:
1) temporarily size the array to the maximum number of files
2) keep track of found files
3) finally resize array to actual number of found files
As follows (I only show relevant snippet):
ii = -1 '<<< initialize the counter fo found files to -1: it's more convenient for its subsequent updating and usage
ReDim outputarray(0 To 2, 0 To Folder.Files.Count) As Variant ' <<< temporarily size the array to the maximum number of files
For Each File In Folder.Files
Set oFS = CreateObject("Scripting.FileSystemObject")
'Set w2 = File
filePath = File.Path
strFilename = File.Name
dateC = File.dateCreated
If InStr(LCase(File.Path), LCase("xls")) <> 0 Then
Set w2 = Workbooks.Open(filePath)
For lRow2 = 1 To w2.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
If w2.Sheets(1).Range("A" & lRow2).Value = "Test Name" Then
ii = ii + 1 '<<< update the number of found files
outputarray(0, ii) = strFilename
outputarray(1, ii) = filePath
outputarray(2, ii) = dateC
End If
Next lRow2
w2.Close False
End If
Set oFS = Nothing
Next File
ReDim Preserve outputarray(0 To 2, 0 To ii) As Variant '<<< finally resize array to actual number of found files
edit
BTW you can avoid the double nested writing loops and use a one shot statement:
w.Sheets("ControlSheet").Range("A1").Resize(UBound(outputarray, 1) + 1, UBound(outputarray, 2) + 1).Value = outputarray
I want to open a txt-File, read the textlines into arrays, delete specific arrays and write all those textlines into another textfile.
It might be easier to understand if you read the code:
Sub:
Open "G:\Arbeit\gen molding\Molding.spf" For Input As #1 'code from textfile below
Dim i As Integer
Dim tlmold() As String
Do Until EOF(1) 'read into array
ReDim Preserve tlmold(i)
Line Input #1, tlmold(i)
i = i + 1
Loop
Close #1
DeleteFromArray tlmold, "M17" 'function code below
DeleteFromArray tlmold, "I_R828"
*DeleteFromArray tlmold, "I_R872"*
Dim tllength As Integer
tllength = UBound(tlmold)
For i = tllength To 0 Step -1 'newtext is the text for the new txt-file
newtext = newtext & tlmold(i) & vbCrLf
Next i
newtext = Replace(newtext, "ÿþ", "") 'remove BOM
Set Fileout = fso.CreateTextFile("G:\Arbeit\gen molding\Molding2.spf", True, True) 'create new textfile
Fileout.Write newtext
Fileout.Close
Function:
Function DeleteFromArray(ByRef Arr As Variant, StringToBeDeleted As String)
Dim arrlength As Integer
Dim strtest As String
arrlength = UBound(Arr)
strtest = StringToBeDeleted
For i = 0 To arrlength
strtest = Arr(i)
If InStr(strtest, StringToBeDeleted) <> 0 Then
Arr(i) = ""
ReDim Preserve Arr(arrlength - 1)
Exit Function
End If
Next i
End Function
Textfile "MOLDING.SPF":
G01 Z=0.1
G01 X=24.371 Z=-0.886
G03 X=24.370 Z=-1.040 CR=15.075
G01 X=24.126 Z=-12.934
G02 X=24.121 Z=-13.232 CR=50.500
G01 X=I_R830 *Z=-I_R872* ;MOLDING END PT
G01 *Z=-I_R872*-1.200
G01 X=I_R828
M17
The problem is while deleting I_R872 from the textfile, my function does notReDim the array a second time.
Because I_R872 is two times in the textfile.
So the array tlmold(5), which shouldn't exist, is just empty.
I hope you understand my "code" and can help me with my problem.
Thanks in Advance
The easiest way to accomplish what you are trying to do is simply not to place the unwanted text into the array in the first place:
Open "G:\Arbeit\gen molding\Molding.spf" For Input As #1 'code from textfile below
Dim i As Long
Dim j As Long
Dim tlmold() As String
Dim lineIn as String
Dim wanted As Boolean
Dim unwantedText
unwantedText = Array("M17","I_R828","I_R872")
Do Until EOF(1) 'read into array
'Read an input line
Line Input #1, lineIn
'Now decide whether we want that record
wanted = True
For j = LBound(unwantedText) To UBound(unwantedText)
If InStr(lineIn, unwantedText(j)) > 0 Then
wanted = False
Exit For
End If
Next
'If we want this record, re-dimension the array and store the value
If wanted Then
ReDim Preserve tlmold(i)
tlmold(i) = lineIn
i = i + 1
End If
Loop
Close #1
Dim tllength As Integer
'...
An alternative way to bypass arrays and loops is to work with the entire text of the file
Option Explicit
Public Sub UpdateFile()
Const FPATH = "G:\Arbeit\gen molding\"
Const SRC_FILE = FPATH & "Molding.spf"
Const DST_FILE = FPATH & "Molding2.spf"
Dim fullFile As String
Open SRC_FILE For Binary As #1
fullFile = Space$(LOF(1)) 'Read entire file into variable fullFile
Get #1, , fullFile
Close #1
fullFile = Replace(fullFile, "M17", vbNullString)
fullFile = Replace(fullFile, "I_R828", vbNullString)
fullFile = Replace(fullFile, "ÿþ", vbNullString)
Open DST_FILE For Output As #1
Print #1, fullFile 'Write contents back to the new file
Close #1
End Sub
Using newtext = Join(tlmold,vbCrLf) is much faster than the loop below:
For i = tllength To 0 Step -1 'newtext is the text for the new txt-file
newtext = newtext & tlmold(i) & vbCrLf
Next i
You could also use the Scripting.FileSystemObject to read the file. I refactored your code using a StringBuilder instead of an array. StringBuilders are optimized for concatenating strings.
Sub CreateNewSPF()
Const SPF_FILENAME1 = "G:\Arbeit\gen molding\Molding.spf"
Const SPF_FILENAME2 = "G:\Arbeit\gen molding\Molding2.spf"
Const ForReading = 1
Const ForWriting = 2
Dim lineIn As String
Dim fso As Object, StringBuilder As Object, TextStream1 As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set StringBuilder = CreateObject("System.Text.StringBuilder")
Set TextStream1 = fso.OpenTextFile(SPF_FILENAME1, ForReading)
Do Until TextStream1.AtEndOfStream
lineIn = TextStream1.ReadLine
If isValidSPF(lineIn) Then StringBuilder.Append_3 lineIn & vbCrLf
Loop
TextStream1.Close
StringBuilder.Replace "ÿþ", ""
Set Fileout = fso.CreateTextFile(SPF_FILENAME2, True, True) 'create new textfile
Fileout.Write StringBuilder.ToString
Fileout.Close
End Sub
Function isValidSPF(lineIn As String) As Boolean
Dim v As Variant
For Each v In Array("M17", "I_R828", "I_R872")
If InStr(1, lineIn, v, vbTextCompare) > 0 Then Exit Function
Next
isValidSPF = True
End Function
I have a database of about 140,000 test files. I am looking to loop through each folder and pull information from the file name of text and excel files so as to organize the data a little better.
I have found ways to pick a folder path and import information about each file using the code below. This works great except I would like to only pull information from excel and text files and I would also like to pull additional text information from the filename as well. For example I might have a file named:
"444555_CAT1010EL_650-700-800C-2hr laging NOT CH4.txt"
And I would want to print:
the 6 numbers at the beginning of the name (they could be anything) in this example "444555" in one column
print the 3 letters (they could be anything) before "1010EL" in another column. In this example "CAT"
"CH4" in the final column OR even have a column for "CH4" and if the filename contains "CH4" put an X in that column
have a column for "laging" and if the filename contains "laging" anywhere put an X in that column
Thank you in advance for your help.
Sub Compile3()
Dim oShell As Object
Dim oFile As Object
Dim oFldr As Object
Dim lRow As Long
Dim iCol As Integer
Dim vArray As Variant
vArray = Array(10, 0, 1, 156, 2, 4, 144, 146, 183, 185)
'0=Name, 31=Dimensions, 1=Size, 163=Vertical Resolution
Set oShell = CreateObject("Shell.Application")
'-------------------ROW INFO INPUT OPTIONS-----------------
'' 1)
' lRow = 1
' 2) find first empty row in database for bottletracker
'
Dim iRow As Long
iRow = Cells.find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row
lRow = iRow
'------------------------------------------------------------
With Application.FileDialog(msoFileDialogFolderPicker)
.title = "Select the Folder..."
If .Show Then
Set oFldr = oShell.Namespace(.SelectedItems(1))
With oFldr
'Column header information
For iCol = LBound(vArray) To UBound(vArray)
Cells(lRow, iCol + 4) = .getdetailsof(.items, vArray(iCol))
Next iCol
For Each oFile In .items
lRow = lRow + 1
For iCol = LBound(vArray) To UBound(vArray)
Cells(lRow, iCol + 4) = .getdetailsof(oFile, vArray(iCol))
Next iCol
Next oFile
End With
End If
End With
End Sub
I'd use this code. There's three separate procedures at the end that find the last cell on the sheet, return the folder and return all files within the folder.
The main code then looks at each file name and pulls the required information from it.
Note, this code: InStr(sFileName, "CAT") <> 0 will return TRUE/FALSE depending if the text "CAT" is within the file name. InStr(sFileName, "CAT") returns the position of "CAT" within the text, and <>0 turns that into a boolean depending on if it's different from 0.
Option Explicit
Public Sub Test()
Dim sFolder As String
Dim cFiles As Collection
Dim vFile As Variant
Dim sFileName As String
Dim rLastCell As Range
sFolder = GetFolder("S:\DB_Development_DBC\") & Application.PathSeparator
Set cFiles = New Collection
EnumerateFiles sFolder, "*.xls*", cFiles
EnumerateFiles sFolder, "*.txt", cFiles
With ThisWorkbook.Worksheets("Sheet1")
For Each vFile In cFiles
Set rLastCell = LastCell(ThisWorkbook.Worksheets("Sheet1")).Offset(1) 'Find last row
sFileName = Mid(vFile, InStrRev(vFile, Application.PathSeparator) + 1) 'Get just file name from path.
.Cells(rLastCell.Row, 1) = Left(sFileName, 6) 'First 6 characters.
.Cells(rLastCell.Row, 2) = Mid(sFileName, InStr(sFileName, "1010EL") - 3, 3) '3 characters before 1010EL.
.Cells(rLastCell.Row, 3) = InStr(sFileName, "CH4") <> 0 'Contains CH4.
.Cells(rLastCell.Row, 4) = InStr(sFileName, "laging") <> 0 'Contains laging.
Next vFile
End With
End Sub
Sub EnumerateFiles(ByVal sDirectory As String, _
ByVal sFileSpec As String, _
ByRef cCollection As Collection)
Dim sTemp As String
sTemp = Dir$(sDirectory & sFileSpec)
Do While Len(sTemp) > 0
cCollection.Add sDirectory & sTemp
sTemp = Dir$
Loop
End Sub
Function GetFolder(Optional startFolder As Variant = -1) As Variant
Dim fldr As FileDialog
Dim vItem As Variant
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
If startFolder = -1 Then
.InitialFileName = Application.DefaultFilePath
Else
If Right(startFolder, 1) <> "\" Then
.InitialFileName = startFolder & "\"
Else
.InitialFileName = startFolder
End If
End If
If .Show <> -1 Then GoTo NextCode
vItem = .SelectedItems(1)
End With
NextCode:
GetFolder = vItem
Set fldr = Nothing
End Function
Public Function LastCell(wrkSht As Worksheet, Optional Col As Long = 0) As Range
Dim lLastCol As Long, lLastRow As Long
On Error Resume Next
With wrkSht
If Col = 0 Then
lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row
Else
lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
lLastRow = .Columns(Col).Find("*", , , , xlByColumns, xlPrevious).Row
End If
If lLastCol = 0 Then lLastCol = 1
If lLastRow = 0 Then lLastRow = 1
Set LastCell = wrkSht.Cells(lLastRow, lLastCol)
End With
On Error GoTo 0
End Function
Edit:
I've updated the code to include the other requirements and moved finding the last cell to within the loop so it actually works.
Note:
Mid(sFileName, InStr(sFileName, "1010EL") - 3, 3) - this code will throw an error if the text doesn't contain 1010EL. Add a check that InStr(sFileName, "1010EL") <> 0 before letting that line execute.
I need to replace 108 images in word. I wrote VBA code so that for each inline image read in the document, the image will be replace by a new image. The new image is specified by a array that has filepaths in each element. The array comes from a text file.
For some reason, my code won't work if I have my variable, strPath as
strPath = dataArray(i)
or
strPath = Chr(34) & dataArray(i) & Chr(34)
What does work is if I type in
dataArray(0) = "C:\IMGS\G.2.1\NZ_DWH_v_SIMAP_AR1_biovalbox1_1100-1400m_Apr20-May26.png"
The path in the textfile is
C:\IMGS\G.2.1\NZ_DWH_v_SIMAP_AR1_biovalbox1_1100-1400m_Apr20-May26.png
I have 108 lines in the textfile, each for the image that needs to be replaced.
I have displayed the path in a message box and it looks like the above, so I am not sure why I can't get file paths from an array. Can someone help me?
'1-loop thru all figs
'2-bring up box to select figure
'3-add figure
Dim intChoice As Integer
Dim strPath As String
Dim objPic As InlineShape
Dim intCount As Integer
'import text
Dim dataArray() As String
Dim i As Integer
Dim g As Integer
strFileName = "C:\Users\cturner\Desktop\filesimgs_order.txt"
Open strFileName For Input As #1
dataArray = Split(Input$(LOF(1), #1), vbLf)
Close #1
g = 0
intCount = ActiveDocument.InlineShapes.Count
'loop through inline shapes
For i = 0 To intCount
strPath = Chr(34) & dataArray(i) & Chr(34)
MsgBox (TypeName(strPath))
g = g + 1
'check if valid filepath
'Debug.Print FileExists(strPath)
MsgBox strPath
'check if the current shape is an picture
If ActiveDocument.InlineShapes.Item(g).Type = wdInlineShapePicture Then
Set objPic = ActiveDocument.InlineShapes.Item(g)
objPic.Select
'insert the image
Selection.InlineShapes.AddPicture FileName:= strPath, _
LinkToFile:=False, SaveWithDocument:=True
End If
Next i
End Sub
Suprise Suprise, I forgot to trim the carriage return vbCr. After I got that out, code works fine and I am able to replace my buttload of images.
Part 1. I checked my string if it has carriage return. Main problem is that I didn't clean my string, and thus putting it into a function made vba throw the error message (no bueno). If you have it, UBound should = 1
For i = 0 To 2
strPath = dataArray(i)
checkcr = Split(strPath, vbCr)
firstIndex = LBound(checkcr)
lastIndex = UBound(checkcr)
MsgBox (firstIndex)
MsgBox (lastIndex)
MsgBox checkcr(lastIndex)
newstrPath = Replace(strPath, vbCr, "")
MsgBox newstrPath
Next i
Part 2. Corrected Code + bonus. Bouns: some code to check if the file exists (from here )
fix:
newstrPath = Replace(strPath, vbCr, "")
Updated Code:
Sub replacefigs()
' replacefigs Macro
' To replace old figures with new figures (updated disclosure)
'0-get full file paths from textfile
'1-loop thru all figs
'2-bring up box to select figure
'3-add figure
Dim intChoice As Integer
Dim strPath As String
Dim objPic As InlineShape
Dim intCount As Integer
'import text
Dim dataArray() As String
Dim i As Integer
Dim g As Integer
strFileName = "C:\Users\cturner\Desktop\filesimgs_order.txt"
Open strFileName For Input As #1
dataArray = Split(Input$(LOF(1), #1), vbLf)
Close #1
g = 0
intCount = ActiveDocument.InlineShapes.Count
'loop through inline shapes
For i = 0 To intCount
strPath = dataArray(i)
'Get rid of carriage returns
newstrPath = Replace(strPath, vbCr, "")
g = g + 1
'to check if file exists
'Debug.Print FileExists(newstrPath)
'check if the current shape is an picture
If ActiveDocument.InlineShapes.Item(g).Type = _
wdInlineShapePicture Then
Set objPic = ActiveDocument.InlineShapes.Item(g)
objPic.Select
'insert the image
Selection.InlineShapes.AddPicture FileName:= _
newstrPath, LinkToFile:=False, _
SaveWithDocument:=True
End If
Next i
End Sub
I'm lost, I try to fill arrays and receive a type mismatch
I'm trying to fill 4 arrays from one file
There is 500 lines in the text document each holding 4 different types of data separated by ","
The .txt file format example --->
pear, apple, grape, orange
apple, pear, orange, grape
ect...
Here is my code:
Private Sub CmdRun_Click()
Dim ticketid(500) As Variant
Dim theatreid(500) As Variant
Dim ticketamount(500) As Variant
Dim paymethod(500) As Variant
Open "C:\Users\Dylaan\Desktop\School Solution\tickets.txt" For Input As #1
Do While Not EOF(1)
Input #1, ticketid(), theatreid(), ticketamount(), paymethod()
lstticketid.AddItem ticketid()
lsttheatreid.AddItem theatreid()
lstticketamount.AddItem ticketamount()
lstmethod.AddItem paymethod()
Exit Do
Loop
Close #1
End Sub
Why?
take a look on this:
Private Sub CmdRun_Click()
Dim ticketid(500) As Variant
Dim theatreid(500) As Variant
Dim ticketamount(500) As Variant
Dim paymethod(500) As Variant
dim ix as integer
Open "C:\Users\Dylaan\Desktop\School Solution\tickets.txt" For Input As #1
ix = 0
Do While Not EOF(1)
Input #1, ticketid(ix), theatreid(ix), ticketamount(ix), paymethod(ix)
lstticketid.AddItem ticketid(ix)
lsttheatreid.AddItem theatreid(ix)
lstticketamount.AddItem ticketamount(ix)
lstmethod.AddItem paymethod(ix)
ix = ix + 1
Loop
Close #1
End Sub
And of course you should consider to use
freefile (to get a filehandle)
and also the possibility that there are MORE records than expected ...
Set fso = CreateObject("Scripting.FileSystemObject")
Set srcfile = fso.GetFile("c:\myfile.txt")
If err.number = 0 then Set TS = srcFile.OpenAsTextStream(1, 0)
Src=ts.readall
Arr1=Split(Src, vbcrlf)
For Each thing in Arr1
Arr2=Split(thing, ",")
For Each thing2 in Arr2
msgbox thing2
Next
Next
This is vbscript but will work in VB6. We are using the split command.
Some comments on your code:
You don't need to declare those arrays as variants, you can declare them as arrays of strings.
As the file is just 500 lines you can read it in at once.
Your real problem is the input command: It can't read in arrays at once.
The same applies to the listbox: You can't add an array at once.
With all that applied have a look at the following test project:
'1 form with:
' 1 command button : name=Command1
' 4 listbox controls : name=List1 name=List2 name=List3 name=List4
Option Explicit
Private Sub Command1_Click()
Dim strData As String
strData = ReadFile("c:\temp\file.txt")
ShowData strData
End Sub
Private Sub Form_Resize()
Dim sngWidth As Single
Dim sngCmdHeight As Single
Dim sngLstWidth As Single, sngLstHeight As Single
sngWidth = ScaleWidth
sngCmdHeight = 315
sngLstHeight = ScaleHeight - sngCmdHeight
sngLstWidth = sngWidth / 4
List1.Move 0, 0, sngLstWidth, sngLstHeight
List2.Move sngLstWidth, 0, sngLstWidth, sngLstHeight
List3.Move 2 * sngLstWidth, 0, sngLstWidth, sngLstHeight
List4.Move 3 * sngLstWidth, 0, sngLstWidth, sngLstHeight
Command1.Move 0, sngLstHeight, sngWidth, sngCmdHeight
End Sub
Private Function ReadFile(strFile As String) As String
Dim intFile As Integer
Dim strData As String
intFile = FreeFile
Open strFile For Input As #intFile
strData = Input(LOF(intFile), #intFile)
Close #intFile
ReadFile = strData
End Function
Private Sub ShowData(strData As String)
Dim lngLine As Long
Dim strLine() As String
Dim strPart() As String
strLine = Split(strData, vbCrLf)
For lngLine = 0 To UBound(strLine)
strPart = Split(strLine(lngLine), ",")
If UBound(strPart) = 3 Then
List1.AddItem strPart(0)
List2.AddItem strPart(1)
List3.AddItem strPart(2)
List4.AddItem strPart(3)
Else
'not the correct number of items
End If
Next lngLine
End Sub
When you click on Command1 it will read in the textfile from c:\temp\file.txt
After that it will split the data to form an array of lines, loop over all lines, split each line into part, and show the parts in the listboxes, if there are exactly 4 parts on a line.