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
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 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 putting data from the clipboard into my array and splitting it by new lines. But I also need a second dimension splitted by tabs, but don't know how? The data in clipboard is supposed to have a fixed size, so the number of parts will be the same for each line.
What I have so far
Private Sub btnPaste_Click()
Dim Clipboard As MSForms.DataObject
Dim arrClip As Variant
Dim i As Long
Dim str As String
Dim msg As String
On Error GoTo ERRORHAND
Set Clipboard = New MSForms.DataObject
Clipboard.GetFromClipboard
str = Clipboard.GetText(1)
arrClip = Split(str, vbLf)
For i = LBound(arrClip) To UBound(arrClip)
msg = msg & arrClip(i) & vbLf
Next
MsgBox (msg)
Exit Sub
ERRORHAND:
If Err <> 0 Then Debug.Print Err.Description
End Sub
This gives me an array with new elements on each new line from clipboard, but I don't know how to add elements to a second dimension on each 'tab' found in clipboard?
Example of data in clipboard and how I want it to fill the array
Data in clipboard
Data00 Data10 Data20 Data30
Data01 Data11 Data21 Data31
Data02 Data12 Data22 Data32
Data03 Data13 Data23 Data33
etc...
Should be corresponding array element
Array(0,0) Array(1,0) Array(2,0) Array(3,0)
Array(0,1) Array(1,1) Array(2,1) Array(3,1)
Array(0,2) Array(1,2) Array(2,2) Array(3,2)
Array(0,3) Array(1,3) Array(2,3) Array(3,3)
etc...
This is your code with some adds (hope it helps)
Sub btnPaste_Click()
Dim Clipboard As MSForms.DataObject
Dim arrClip As Variant
Dim i As Long
Dim str As String
Dim msg As String
Dim arrClip2 As Variant
Dim arrClipBid() As Variant
Dim ii As Integer
'On Error GoTo ERRORHAND
Set Clipboard = New MSForms.DataObject
Clipboard.GetFromClipboard
str = Clipboard.GetText(1)
arrClip = Split(str, vbLf)
ReDim arrClipBid(LBound(arrClip) To UBound(arrClip), 0 To 0)
For i = LBound(arrClip) To UBound(arrClip)
arrClip2 = Split(arrClip(i), Chr(9))
If MaxLen < UBound(arrClip2) Then
MaxLen = UBound(arrClip2)
ReDim Preserve arrClipBid(LBound(arrClip) To UBound(arrClip), 0 To MaxLen)
End If
For ii = LBound(arrClip2) To UBound(arrClip2)
arrClipBid(i, ii) = arrClip2(ii)
msg = msg & "(" & i & ", " & ii & ")" & arrClip2(ii)
Next ii
msg = msg & vbLf
Next
MsgBox (msg)
Exit Sub
ERRORHAND:
If Err <> 0 Then Debug.Print Err.Description
End Sub
I am trying to display information from a text file into a multiline textbox. I run the code but the system displays an error message 'Index was outside the bounds of the array'. There are no obvious error messages and I can't seem to manipulate the code to get rid of this problem. Take a look:
Public Class TeachCon
Dim layout As String
Dim Contacts(6) As Details
Structure Details
Dim Name As String
Dim Email As String
Dim RoomNum As String
Dim number1, number2 As Integer
End Structure
Sub LoadTeachContacts(ByRef Contacts() As Details)
Dim TextFile As String = "\\Sjcdom01\mstudent\LHeywood\documents\A2\Computing\Comp 4 - Smail\Project\Text Files\Teacher Contact List.txt"
Dim TextLine As String = ""
Dim ArrayCounter As Integer = 0
Dim objReader As New System.IO.StreamReader(TextFile)
'loop through text file and load all contacts
Do While objReader.Peek() <> -1
'read next line from file
TextLine = TextLine & objReader.ReadLine() & vbNewLine
'declare an array and use it to split line from file
Dim TempArray() As String = Split(TextLine, ",")
'transfer each array element into the appropriate part of the contacts stucture
Contacts(ArrayCounter).Name = TempArray(0)
*Contacts(ArrayCounter).Email = TempArray(1)*
Contacts(ArrayCounter).RoomNum = TempArray(2)
Contacts(ArrayCounter).number1 = TempArray(3)
Contacts(ArrayCounter).number2 = TempArray(4)
'empty string before reading next line from file
TextLine = ""
'increment array counter
ArrayCounter = ArrayCounter + 1
Loop
End Sub
Private Sub ButShow_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim ArrayCounter As Integer = 0
LoadTeachContacts(Contacts)
Do Until ArrayCounter = 3
layout = Contacts(ArrayCounter).Name & "," & Contacts(ArrayCounter).Email & "," & Contacts(ArrayCounter).RoomNum & "," & Contacts(ArrayCounter).number1 & "," & Contacts(ArrayCounter).number2
If ArrayCounter = 0 Then
TextBox7.Text = layout
End If
ArrayCounter += 1
Loop
End Sub
End Class
The text enclosed by the * is where the system says it is outside the bounds of the array.
Well, one of your lines probably splits into an array that is shorter than you expect, and hence the index does not exist. Check the length of the array before you get the value. Maybe something like this
If TempArray.Length > 0 Then Contacts(ArrayCounter).Name = TempArray(0)
If TempArray.Length > 1 Then Contacts(ArrayCounter).Email = TempArray(1)
If TempArray.Length > 2 Then Contacts(ArrayCounter).RoomNum = TempArray(2)
If TempArray.Length > 3 Then Contacts(ArrayCounter).number1 = TempArray(3)
If TempArray.Length > 4 Then Contacts(ArrayCounter).number2 = TempArray(4)
Don't know exactly what your TextFile contains in it. But inorder to handle the exception change the code as below
'declare an array and use it to split line from file
Dim TempArray() As String = Split(TextLine, ",")
'transfer each array element into the appropriate part of the contacts stucture
If TempArray.Length > 0 Then
Contacts(ArrayCounter).Name = TempArray(0)
*Contacts(ArrayCounter).Email = TempArray(1)*
Contacts(ArrayCounter).RoomNum = TempArray(2)
Contacts(ArrayCounter).number1 = TempArray(3)
Contacts(ArrayCounter).number2 = TempArray(4)
End If
'empty string before reading next line from file
TextLine = ""
It would be helpful if you could give the content of the file also:
"\Sjcdom01\mstudent\LHeywood\documents\A2\Computing\Comp 4 - Smail\Project\Text Files\Teacher Contact List.txt"
I think that you should check if the line is empty or not, because the item 0 will be available without error as a Null String, but the item 1 will throw 'Index was outside the bounds of the array' In LoadTeachContacts Sub
'read next line from file
If objReader.ReadLine().Trim = "" Then Continue Do
TextLine = TextLine & objReader.ReadLine() & vbNewLine
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.