Skip to content Skip to sidebar Skip to footer

Visual Vasic Studio Read Text File Into Array

  1. #1

    Daniel Duta is offline

    Thread Starter

    Hyperactive Member Daniel Duta's Avatar


    Resolved [RESOLVED] How to load properly a text file in an array?

    Hello all,
    I desire to load some text files (which comprise data tab separated) in a bidimensional array directly.
    The outcome is each file has a variable number of columns and I do non know how to redimension in run-time
    the showtime dimension of my array accordingly with number of columns of the file. Is it possible?
    To accept starting point I post below my work schema :

    Code:

    Private Sub btnInput_Click()     Dim fnum As Integer, i As Long, k every bit byte 'cannot be more than 30 columns ...     Dim myArray() As String, pathFile As String      pathFile = App.Path & "\myFile.txt"      'ReDim should exist done in run fourth dimension just how ....     ReDim myArray(1 To grand, 10000)     fnum = FreeFile      Open pathFile For Input As #fnum         i = 0     Practise While Not EOF(fnum) 'Check for end of file         Input #fnum, myArray(one, i), myArray(ii, i), myArray(3, i), myArray(four, i), ..........         i = i + 1     Loop     Close #fnum     ReDim Preserve myArray(one To chiliad, i) End Sub

  2. #two

    Re: How to load properly a text file in an assortment?

    Why practice you lot need a 2-dim array? All you are doing is putting a number in your 2-dim assortment, which is the what the element number of a 1-dim assortment is.
    look at the split() function....using that with vbTab, you tin put each partial cord into its appropriate assortment, and access information technology past:

    myArray(ane), myArray(ii), etc, and y'all will come across your strings.


  3. #3

    Re: How to load properly a text file in an assortment?

    One manner to create a ragged array is to employ variants.
    An example. In the push I first had the lawmaking to create a sample file.
    After the file was created, I commented that out and reused the button to "parse" the file.
    It first splits the file by lines.
    It then creates an array of variants, i for each line.
    Information technology then splits each line using the tab and that array is assigned to the "Line" or "Row" variant.
    It prints out the final field of the commencement 10 rows, so yous can encounter that they are varying (Col of Cols indicates how many columns were in that row).

    Whether this is "proper", I can't say. Information technology is 1 style.

    Lawmaking:

    Option Explicit  Dim raggedMatrix() As Variant  Individual Sub Command1_Click() ''Code to generate a test file, 100 lines with varying columns from 10 to 30 '  Dim i Equally Integer, j Equally Integer '  Dim n Equally Integer ' '  Open "C:\c\TestFile.dat" For Output As #1 '  For i = 1 To 100 '    n = 10 + Rnd() * 20 '    For j = ane To n '      Impress #1, "Line " & CStr(i) & " Col " & CStr(j) & " of " & CStr(n); '      If j <> due north And so Impress #1, vbTab; '    Next '    Impress #ane, "" 'a new line '  Next '  Close #i    Dim fileContents As String   Open up "C:\c\TestFile.dat" For Binary As #ane     fileContents = Infinite$(LOF(1))     Get #1, , fileContents   Shut #1    Dim Lines() Equally String   Lines = Split(fileContents, vbCrLf)    ReDim raggedMatrix(UBound(Lines))    Dim i As Integer   For i = 0 To UBound(Lines)     raggedMatrix(i) = Divide(Lines(i), vbTab)   Next  'Test past printing the last element of the first 10 rows    For i = 0 To 9     Debug.Print raggedMatrix(i)(UBound(raggedMatrix(i)))   Next  End Sub
    Example output

    Lawmaking:

    Line 1 Col 24 of 24 Line ii Col 21 of 21 Line three Col 22 of 22 Line 4 Col xvi of 16 Line 5 Col sixteen of xvi Line 6 Col 25 of 25 Line 7 Col 10 of 10 Line 8 Col 25 of 25 Line nine Col 26 of 26 Line x Col 24 of 24
    Last edited by passel; Jun 10th, 2014 at 03:21 PM.

  4. #4

    Re: How to load properly a text file in an assortment?

    The best way, as I idea is to piece of work with 1 dimension array and use an showtime to logicaly move to next row.

  5. #5

    Re: How to load properly a text file in an array?

    Exactly (to both of you (and op)). Carve up into a one dim array. (Equally shown in #3, and suggested in #4 and my postal service).

  6. #half-dozen

    Re: How to load properly a text file in an assortment?

    For that to work, since the number items in a row differ, you would have to continue track of the get-go to the next row in some manner, i.e. use a link list structure, or a separate index array. Knowing how to size the array efficiently would exist an issue would be an effect too, you can't know how large to make the assortment until you've read all the data. You could ever go for worse case, once you've dissever the lines, and go with 30 * number of rows, in which case you wouldn't need the index assortment as you could but exit some strings unused, then each "row" would always begin on a multiple of 30 array index.

    Of class, you could only read the lines into an array, and merely split the lines by tab character as you need them.
    I would also, knowing at that place is a limit of 30 columns, be tempted to create a 2D array of strings, (1 to 30, RowCount), since the unused strings in the 1 to 30 (or 0 to 29 if yous choose) would not waste matter too much information.
    Information technology actually comes downwards to usage. How often practise you need to access the columns of information.


  7. #vii

    Re: How to load properly a text file in an array?

    Upon re-reading the original post, I think I misread it. I was thinking the number of columns varied within a file, just I think you are saying that the number of columns differ betwixt files, not within a file.
    So, if you read the first line from a given file and split it and then you lot know how many columns are in the file, you could then read the file in and split to observe the number of rows, and then dimension the assortment accordingly.

    If yous needed to redimension and preserve a multidimensional array, than can only be done when changing the last dimension.
    You tin't preseve the data in a multidimensional array if yous alter any alphabetize other than the terminal, because that would change the "cake size" of the aggregated left dimensions.

    Redim preserve is perchance a convenience, but it is expensive to utilize repeatedly. Information technology is usually quicker to read a file twice, once to find how much storage you need, and simply redim once, than to continually expand the array as y'all process the file.

    Final edited past passel; Jun tenth, 2014 at 03:48 PM.

  8. #viii

    Re: How to load properly a text file in an array?

    This is mArray.cls equally I used it in M2000 Interpreter, as a container for arrays. I accept a limit of 10 dimensions. Study it. Used for string or arithmetic values

    Code:

    Dim mmname As String Dim dnum As Long Dim limit(10) Equally Long  ' max ten dimensions Dim dtable(ten) Equally Long Dim actualdata() As Variant Dim maxitems As Long  Public Holding Let arrname(aName Every bit String) mmname = aName Terminate Property Public Property Become arrname() Every bit Cord arrname = mmname End Property Public Sub PushDim(nDim Equally Long) ' dim an assortment pushin 1 by one the new nDim If dnum < 10 Then limit(dnum) = nDim maxitems = maxitems * nDim dnum = dnum + 1 Finish If Stop Sub Public Sub PushEnd() On Error GoTo there11 If dnum = 0 Then maxitems = 1 ReDim actualdata(maxitems) As Variant Else ReDim Preserve actualdata(maxitems) As Variant Dim i As Long, mx As Long mx = maxitems For i = 0 To dnum - 1     dtable(i) = mx / limit(i)     mx = dtable(i) Next i Stop If Exit Sub there11: dnum = 0 maxitems = one ReDim actualdata(maxitems) End Sub Public Sub StartResize() dnum = 0 ' no actions maxitems = one Terminate Sub Public Part SerialItem(Item As Variant, cursor Equally Long, control As Long) Equally Boolean If command = 1 And so If mdim = 0 So Leave Function If cursor < 0 Or cursor >= maxitems Then Get out Role actualdata(cursor) = Item ElseIf command = 2 Then If mdim = 0 Then Go out Part If cursor < 0 Or cursor >= maxitems Then Exit Function Item = actualdata(cursor) ElseIf command = 3 So Fill up Item ElseIf command = 4 And so cursor = maxitems ElseIf command = five So cursor = dnum Particular = dnum ElseIf command = half-dozen Then If cursor > 9 Or cursor < 0 Then Item = 0 Else Detail = limit(cursor) Terminate If ElseIf command = 7 And then  'erase all information Dim aa As Variant Fill aa ElseIf control = viii And so If dnum = one Then ReDim Preserve actualdata(cursor) As Variant maxitems = cursor limit(0) = maxitems End If End If SerialItem = True  Stop Function  Public Role PushOffset(curitem As Long, curdim Equally Long, nDim As Long) As Boolean If curdim >= dnum Then ' error... PushOffset = Fake Else If nDim >= limit(curdim) And so Exit Role curitem = curitem + dtable(curdim) * nDim PushOffset = Truthful End If End Function Public Holding Get Detail(curitem As Long) As Variant Detail = actualdata(curitem) Finish Property Public Holding Let Detail(curitem As Long, Item Every bit Variant) actualdata(curitem) = Item Cease Holding Private Sub Fill(Item Equally Variant) If dnum > O And so Dim i Every bit Long For i = 0 To maxitems - 1 actualdata(i) = Item Next i End If End Sub  Private Sub Class_Initialize() dnum = 0 ' no actions maxitems = 1 ReDim actualdata(0) End Sub  Private Sub Class_Terminate() Erase actualdata() Terminate Sub
    Last edited past georgekar; Jun 10th, 2014 at 04:01 PM.

  9. #9

    Daniel Duta is offline

    Thread Starter

    Hyperactive Fellow member Daniel Duta's Avatar


    Re: How to load properly a text file in an array?

    Hullo all,
    Yeah, the number of columns differs among files and this variation does non allow me to have a certain value (already known) on the first dimension of the array...At present, many of you consider a uni-dimensional array every bit an easier arroyo. I agree but my purpose is non to take a collection of uni-dimensional arrays but to facilitate a convenient manner - simple and fast - of inserting data in Excel that will exist a line like : objExcelApp.Range("A1:X" & Ubound(myArray,2)).Value = objExcelApp.WorksheetFunction.Transpose(myArray)
    Other reasons would be it will be easier to create some charts from array, to select certain columns in analysis then on.
    Thank you for all your suggestions.

  10. #ten

    Re: How to load properly a text file in an assortment?

    If you want to utilize my class this is how yous can practice. Run across the code above to see how you lot can read how many dimensions have and the upper limit for each.

    Code:

    dim afto every bit New mArray  afto.PushDim 10 afto.Pushdim 30 afto.PushEnd  assortment 10 x thirty   afto.startresize afto.PushDim xl afto.PushDim 30 afto.PushEnd  resize array 40x30  (preserved ten outset rows)   find beginning to store or load information  at p1,p2: dn =0  offsetvar=0  ' this is the get-go, it isn't inside class considering  	  	' M2000 has threads that can read aforementioned array same time... ' supposed we take a 2 dimension if not afto.PushOffset(offsetVAr, dn, clng(p1)) and then print "error or practice somethingr" dn=dn+1 if not afto.PushOffset(offsetVAr, dn, clng(p2)) then impress "mistake" afto.item(offsetvar)=itemtostore or retValue=afto.particular(offsetvar) Yous can brand a Function aa() to deed as an array: print aa(p1,p2)
    Last edited by georgekar; Jun tenth, 2014 at 04:47 PM.

  11. #xi

    Re: How to load properly a text file in an array?

    I think if y'all want to keep your 2d assortment you volition accept to use a udt instead of an array.
    It would be easier to redim your udt with two arrays.

  12. #12

    Re: How to load properly a text file in an array?

    If all items accept a tab then you can rename the file as csv and load as a table in Excel

    http://office.microsoft.com/en-us/ex...010099725.aspx

    Concluding edited by georgekar; Jun tenth, 2014 at 05:32 PM.

  13. #13

    Re: How to load properly a text file in an array?

    Quote Originally Posted by SamOscarBrown View Post

    Why do you demand a two-dim array? All you are doing is putting a number in your 2-dim assortment, which is the what the element number of a i-dim array is....

    Nowhere in his code is he putting the array index into the 2-dim array.
    The file is essentially a CSV file, except using tabs instead of comma's to separate the columns.
    The file is two dimensional, each line consisting of up to 30 columns.
    Variable i is not written to the array, it is used (in the second dimension) to admission the row (the line of the file) ,and the numbers, 1,2,3 etc (the showtime dimension) are the columns.

    Anyway, assuming the number of columns doesn't change within a file, then you can create a 2d array of strings to hold the values in the "cells", indexed past row,column.
    A modification of the earlier lawmaking. It moves the column number generation outside the inner loop, so uses the aforementioned number of columns for all lines of the file generated.

    Lawmaking:

    Option Explicit Dim Array2D() As String  Private Sub Command1_Click() ''Code to generate a exam file, 100 lines same number of columns, x to 30, in each line '  Dim i As Integer, j As Integer '  Dim due north As Integer  '  Open "C:\c\TestFile1.dat" For Output As #ane '  n = ten + Rnd() * 20 '  For i = 1 To 100 '    For j = i To n '      Print #ane, "Line " & CStr(i) & " Col " & CStr(j) & " of " & CStr(n); '      If j <> n So Impress #ane, vbTab; '    Next '    Print #1, "" 'a new line '  Next '  Shut #1  ''Create 2nd array bold fixed number of columns per row   Dim fileContents As String   Open "C:\c\TestFile1.dat" For Binary As #1     fileContents = Space$(LOF(1))     Get #1, , fileContents  'Read the file contents into a cord   Shut #1    Dim Lines() As String   Lines = Dissever(fileContents, vbCrLf)  'split out each row of information   Dim cols() As String                 'Array to hold the columns for a given row   cols = Split(Lines(0), vbTab)        'Divide the first row and then we know how many columns we have    ReDim arr2d(UBound(Lines), UBound(cols)) 'Size the array past rows, colunms)    Dim i As Integer, j As Integer   For i = 0 To UBound(Lines)        'For each row in the file     cols = Carve up(Lines(i), vbTab)   '  split out the columns     For j = 0 To UBound(cols)       '  For each cavalcade in a row       arr2d(i, j) = cols(j)         '    Assign the value to the row/column "prison cell"     Adjacent   Next  'Exam past printing the final element of the outset ten rows   For i = 0 To 9     Debug.Print arr2d(i, UBound(arr2d, 2))   Next  Stop Sub
    georgekar, I tin can run across where your course would exist useful in building an interpreter, but I don't remember that it would be more efficient than creating a native 2d assortment. The calculations you take to get through to translate the multidimensional index values into a linear beginning is the same the compiler generated code has to do to do. You may be able to wrap some more flexibility into redimensioning and preserving information than the Native VB allows, only I tin't meet it being faster or less memory intensive than the congenital-in capability of VB6.

    p.south. A few more posts posted while I was composing this. Since the goal is to interact with an Excel spreadsheet, I guess I'll step away. I oasis't had to practice whatever application interops. The to a higher place code volition read the file into a two dimensional array, as was the original asking, I believe, but may not be what you're actually after.

    Last edited by passel; Jun 10th, 2014 at 05:12 PM.

  14. #xiv

    Daniel Duta is offline

    Thread Starter

    Hyperactive Fellow member Daniel Duta's Avatar


    Re: How to load properly a text file in an array?

    Hi,
    Thanks for proposition, Max. An UDT array could be a solution for my needs. I will try tomorrow this approach considering information technology is a bit tardily to me at the moment.

  15. #15

    Re: How to load properly a text file in an array?

    passel,
    My thought nigh the problem of Daniel Duta, is that he has to do two things...one to read at to the lowest degree on row of data and so to expand rows every bit the reading become further. So he need to preserve data, and in vb you can preserve data only when you change the last dimension. Yous think that reversing the gild of dimensions, and brand the rows to be the concluding, then he end with the problem. But the problem exist because he didn't know the number of fields in a row. Then with my class he can make i dimension the array and expand information technology until he achieve the row end, and and then he add rows.

    In your example...first you read all the data in a string, then yous make a copy of that string in an assortment of "lines" and and so you make a re-create of get-go line in an array of "fields", So you accept your time to make full the array. But these are two jobs for one. Because: Afterwards beginning separate yous can erase information technology and make another split from second line..and for each field of the line y'all tin feed the excel or what always ....without whatsoever 2d array for intermediate stage.

    Using my course you have i array expanded row past row as you read data and peradventure follow a validation procedure that skip the job if an error have been founded. My dominion says that if you give air to your code and not to stuck in the formality of the problem and then you tin later expand the projection, no rewrite it.
    My solution isn't the best just add a signal to create someone a better code.

    Last edited by georgekar; Jun 10th, 2014 at 06:11 PM.

  16. #sixteen

    Re: How to load properly a text file in an array?

    Quote Originally Posted past Daniel Duta View Post

    Hi,
    Thanks for proffer, Max. An UDT array could exist a solution for my needs. I volition attempt tomorrow this approach because it is a bit late to me at the moment.

    With an UDT-Array yous volition lose the capability, to straight feed an Xl-Range from your (Variant)-Array.

    I still call back, that passels code in #13 is what you lot need...

    First Separate the Lines into a Lines() Cord-Array -
    then determine the Columns from only the offset line.
    Redim your 2D-assortment now (once) with the right dimensions and start
    looping and filling information technology using your already separate-upwards Lines() array.

    That'south what passels code does - and what'south IMO easiest (and also well-performing).

    Olaf


  17. #17

    Re: How to load properly a text file in an array?

    Although I agree and would probably read whole file at once like passel's lawmaking, the only difference would exist I would become the MAXCOLUMNS of the longest line (the i with the most columns) and set information technology, then parse it.

    Anyways, I came up with this lawmaking.

    You could create 2 arrays instead of udt it would end up the same, just I like working with UDTs when I tin can. I haven't worked with excel sheets but its all rows and columns and then information technology'south pretty straight forward. I used a udt for row text and its column position, rows adds up everytime its back to cavalcade 0.

    Add to form ii commandbuttons
    -Command1 (to load file)
    -Command2 (to exam/load speedsheet)

    Code:

    Individual Const ITEM_LIMIT = 10000  Individual Type UDT_File   RowText() As Cord   ColumnPos() As Integer End Blazon  Individual MyUDT Every bit UDT_File  Individual Sub Command1_Click() Dim sText() Equally String Dim sLine As String Dim sFile As String Dim iNum  As Long Dim FF    Every bit Integer Dim i     As Long    ReDim MyUDT.ColumnPos(ITEM_LIMIT)   ReDim MyUDT.RowText(ITEM_LIMIT)      sFile = "C:\test.txt"      FF = FreeFile      Open sFile For Input As #FF          Exercise Until EOF(FF)       With MyUDT                  Line Input #FF, sLine                      sText = Divide(sLine, vbTab)                        If iNum > UBound(.RowText) Then               ReDim Preserve MyUDT.RowText(UBound(.RowText) + ITEM_LIMIT)               ReDim Preserve MyUDT.ColumnPos(UBound(.ColumnPos) + ITEM_LIMIT)             End If                          For i = 0 To UBound(sText)               .RowText(iNum) = sText(i)               .ColumnPos(iNum) = i               iNum = iNum + 1             Next                    End With     Loop        Shut #FF      ReDim Preserve MyUDT.ColumnPos(iNum - 1)   ReDim Preserve MyUDT.RowText(iNum - one) End Sub  Individual Sub Command2_Click() Dim i As Long Dim Rows Every bit Long    With MyUDT     For i = 0 To 15       If .ColumnPos(i) = 0 And so         Rows = Rows + one         Debug.Print ""       End If       Debug.Print "Row" & Rows & ",Col" & .ColumnPos(i) & " : " & .RowText(i)     Next   Terminate With         'Or into a spreadsheet   Debug.Impress vbNewLine & vbNewLine & "Excel example"   Rows = 0        With MyUDT     For i = 0 To UBound(.RowText)       If .ColumnPos(i) = 0 Then         Rows = Rows + 1       End If       '************************************************************************************       'ExcelSheet.Range(.ColumnPos(i),Rows).Value = .RowText(i) '***** Excel Example ******       '************************************************************************************     Next   End With Cease Sub
    Last edited by Max187Boucher; Jun tenth, 2014 at 09:58 PM.

  18. #xviii

    Re: How to load properly a text file in an assortment?

    Here's my 2 cents:

    Generic Delimited Text File Reader

    Might be overkill, just ought to do what was requested.


  19. #19

    Daniel Duta is offline

    Thread Starter

    Hyperactive Member Daniel Duta's Avatar


    Re: How to load properly a text file in an array?

    Hullo,
    Trying today to bring my csv file in a 2D array I realized that it is not tab delimited but infinite delimited. The worst affair is these spaces are not constant but variable and I actually practice not know how to utilize the Dissever function in these conditions ...I know that this file is a bit atypical - the useful rows are not starting from the first line - but I am just curious if it is possible to handle a file similar that in vb6 without vba support, because I accept noted that Excel tin can split up it properly (simply after I eliminate all useless rows from first). For a improve view I attached a file sample. Cheers all for your valuable suggestions.

  20. #twenty

    Re: How to load properly a text file in an array?

    The file looks organized likewise me.

    If you read the file line by line and then start with dissimilar parsing blocks when the line starts with a "~"
    Ignore all lines starting with "#"
    The first block being "~CURVE INFORMATION"
    Read all lines for the number of columns until you lot go the next block "~A"
    This second block represents an assortment with an unknown number of lines.
    Just read all lines until y'all reach the End Of File.
    All columns accept a width of 13, except the first column, which has a width of x.
    Or replace all double spaces with a single infinite, until there are no double spaces left.
    Then you tin split the line on the space character.


  21. #21

    Re: How to load properly a text file in an assortment?

    I hope this works for you:

    Code:

    Option Explicit  Private Sub Command1_Click()   Dim dValues() As Double      dValues = ParseFile("C:\Users\ArnoutV\Downloads\file1.txt") End Sub  Individual Part ParseFile(sFileName As Cord) As Double()   Dim aData() Equally String, sLine As String, aLine() As Cord   Dim i As Long   Dim lNofLines As Long, lNofColumns As Long   Dim bCountColumns As Boolean, bCountLines As Boolean   Dim lColumn As Long   Dim dValues() As Double, lStartData Equally Long      If FileToArray("C:\Users\ArnoutV\Downloads\file1.txt", aData) Then     For i = 0 To UBound(aData)       sLine = Trim$(aData(i))       If Len(sLine) > 0 Then         If Left$(sLine, i) <> "#" And then           If Left$(sLine, 1) = "~" And then             Select Example sLine               Case "~Curve INFORMATION"                 bCountColumns = Truthful               Instance "~A"                 bCountLines = True                 bCountColumns = Simulated                 lStartData = i + one             End Select           Else             If bCountLines Then lNofLines = lNofLines + ane             If bCountColumns Then lNofColumns = lNofColumns + 1           End If         End If       Cease If     Adjacent i          Debug.Print lNofColumns, lNofLines          ReDim dValues(lNofLines - 1, lNofColumns - i)     For i = lStartData To UBound(aData)       sLine = Trim$(aData(i))       If Len(sLine) > 0 Then         Do While InStr(ane, sLine, "  ", vbBinaryCompare) > 0           sLine = Replace(sLine, "  ", " ")         Loop         aLine = Split(sLine, " ")         For lColumn = 0 To lNofColumns - 1           dValues(i - lStartData, lColumn) = Val(aLine(lColumn))         Side by side lColumn       End If     Next i        End If      ParseFile = dValues Finish Function  Public Role FileToArray(sFileName As String, aData() Every bit String) As Boolean   Dim bBuffer() Equally Byte   Dim sData As String, sSplit Equally String   Dim lPos As Long      If FileToByteArray(sFileName, bBuffer) Then          sData = StrConv(bBuffer, vbUnicode)          If LenB(sData) <> 0 Then              ' initial split on LineFeed       sSplit = vbLf              lPos = InStr(1, sData, vbLf)       If lPos > one So         ' If CarriageReturn earlier LineFeed thenn split on CrLf         If Mid$(sData, lPos - one, 1) = vbCr So sSplit = vbCrLf       End If       aData = Carve up(sData, sSplit)       FileToArray = Truthful     End If   Cease If End Part  Public Part FileToByteArray(sFileName As Cord, btData() Every bit Byte) As Boolean   Dim FileNumber As Integer      If Len(Dir$(sFileName)) > 0 Then     If FileLen(sFileName) > 0 So       FileNumber = FreeFile       Open sFileName For Binary Access Read Every bit #FileNumber       ReDim btData(0 To LOF(FileNumber) - 1)       Get #FileNumber, , btData       Shut #FileNumber       FileToByteArray = Truthful     End If   End If  Finish Function

  22. #22

    Re: How to load properly a text file in an array?

    Well, I kind of don't want to post later on all the work Arnout has washed, simply I did modify the code I had before to work on the file given.
    I observed the same characteristics of the file that Arnout noted, in particular that the starting time column was ten wide and the others thirteen broad, and as well that the data portion of the file was preceded by the "~A" tag.
    I decided to take advantage that the Val office will ignore leading and trailing spaces when converting a number and just treat all the columns as xiii, so the first column has an actress iii spaces on the terminate of the number, and all the other numbers are "shifted", to take leading and trailing spaces.
    Arnout'south is more robust, aka foolproof, because if a number is large enough, my code may cutting off some digits, but if the electric current data is representative, this possibility is not a problem.
    Arnout is also more conscientious about testing for other possible errors that might occur.
    In any case, since its done, I'll mail service it.

    Lawmaking:

    Choice Explicit  Dim arr2d() As Double  Private Sub Command1_Click()    Dim i As Long   Dim fileContents As String   Dim Lines() As Cord   Dim NumOfCols As Long    Open "C:\c\File1.txt" For Binary Every bit #i     fileContents = Space$(LOF(1))     Get #1, , fileContents  'Read the file contents into a string   Close #1    Lines = Split(fileContents, vbCrLf)  'split out each row of information  ' Look for the "~A" tag to know where to start parsing columns   Dim ptr Equally Long   For i = 0 To UBound(Lines)     If InStr(Lines(i), "~A") <> 0 So       ptr = i + i       Exit For     End If   Next    If ptr <> 0 And then 'presume we take data     NumOfCols = Len(Lines(ptr)) \ 13   'actually + one, just we'll utilise this for a 0 based array      ReDim arr2d(UBound(Lines) - ptr - one, NumOfCols) 'Size the array by rows, colunms)      Dim j As Long     For i = ptr To UBound(Lines) - 1     'For each row in the output       For j = 0 To NumOfCols            '  For each cavalcade in a row         arr2d(i - ptr, j) = Val(Mid$(Lines(i), one + 13 * j, 13)) '    Assign the value to the row/column "cell"       Next     Next    'Test by press the showtime two elements and concluding two elements of the concluding five rows to compare to the file     For i = UBound(arr2d, i) - five To UBound(arr2d, 1)       Debug.Impress arr2d(i, 0), arr2d(i, 1), arr2d(i, NumOfCols - ane), arr2d(i, NumOfCols)     Next   End If  End Sub

  23. #23

    Re: How to load properly a text file in an array?

    I only now download the file1.txt.
    This is a report from measurements All values are integers and not float numbers. Y'all see the decimal point but this isn't floating decimal point. And then the all-time mode to translate that information is to throw decimal points and shop values equally integers with existent value div 10000 and [mod 10000] for the decimals..
    The parsing for that file must be in two arrays, one for the names and quality (or what ever yous say in English...) of each column and finally the integer (Long is ameliorate.).

    I Know well-nigh that because I was to be a petroleum engineer....and in academy I wrote a data processor for measurements with integers to play the part of existent numbers, for accuracy (because mantissa in floating signal was a bad experience that days...). My program was in BBC Basic, I make an overlaying system because I had simply 14 Kb Ram, and I reprogram Motorola 6845 VDU chip to go some lines out of display to make it my storing struct. Programming in that conditions are an extraordinary example..now but not for 1988...

    So before a parsing operation start go sure nigh what is valid and what not, it isn't all chars...

    (don't miss that Zip value...the non taken measurement, it mentioned i think equally -999.25 in the file )

    Last edited by georgekar; Jun 12th, 2014 at 12:34 PM.

  24. #24

    Re: How to load properly a text file in an assortment?

    I reworked some existing code into a more generic record parser, which you tin now find at:

    Formatted Text Record Parser

    The included FmtText1 demo Projection processes your sample file. I'yard a picayune mystified why you'd desire arrays with lower bounds of i, but the demo deals with it anyway.

    If you need to process the "null value" you could easily handle that, merely I noticed this value doesn't seem to occur within the data.


  25. #25

    Re: How to load properly a text file in an array?

    This is my solution. With vertical scroll bar you change page. I use a role from M2000 Interpreter to become the value (just I didn't use the double value which that function returns, just the markers to extract merely the chars...)

    This is an sometime version..new is better......
    Name:  example1.JPG  Views: 1070  Size:  51.5 KB

    Last edited by georgekar; Jun 12th, 2014 at 05:00 PM.

  26. #26

    Daniel Duta is offline

    Thread Starter

    Hyperactive Member Daniel Duta's Avatar


    Re: How to load properly a text file in an assortment?

    Hello guys,
    I owe you all a feedback regarding my thread. After I tested many ideas involved in your samples I considered the closest to my thinking and my needs is the passel's approach. So I built the foundation of my function borrowing his primary ideas. Even other parsers could exist more robust (such as those of Arnout, George or Dile) I preferred to have a clear and more readable procedure so that to able to change the code in an like shooting fish in a barrel way if needed. The function detailed beneath does allow me both to load many selected csv files in memory and to use an UDT assortment for each of them.
    In this way each UDT array element volition keep in memory a file and that file could be exported/handled anytime in excel using just i line of code. Otherwise, give thanks you all for your corking support.

    Lawmaking:

    Public Function csvParser(pathFile Equally Cord) As Variant()   Dim i Equally Long, yard As Long, J As Long, fRow As Long   Dim fileContent As String, rng Equally String, header Every bit String   Dim Lines() As Cord, tmpArr() Every bit String   Dim nCols Equally Byte, nRows As Long, tag As Long    Open pathFile For Binary As #1         fileContent = Space$(LOF(1))         Go #1, , fileContent  'Read the file content into a string   Close #i    Lines = Dissever(fileContent, vbCrLf)  'split out each row of data         'Look for the "~A" tag to know where to start parsing columns     For i = 0 To UBound(Lines)        If Trim$(Lines(i)) = "~A" Then          tag = i + ane          header = Trim$(Mid$(Lines(i - ii), 2)) 'nosotros become the header line          Exit For        Terminate If     Next     If tag = 0 And so Exit Function 'we practice not accept data !          'Space normalization in the header cord     Do While InStr(1, header, Space(2)) > 0         header = Replace(header, Space(2), " ")     Loop     tmpArr = Split up(header, " ") 'motility the header in assortment          nCols = UBound(tmpArr) + 1  'nb of cols     nRows = UBound(Lines) - tag + one 'nb of rows (data cake + header)          ReDim myArr(1 To nRows, 1 To nCols) 'Size the array co-ordinate to excel array assumptions     For i = 0 To UBound(tmpArr)         myArr(1, i + one) = tmpArr(i)     Side by side i          fRow = tag - 2 'constant: first row of the data block     For i = 2 To nRows        For J = i To nCols           k = thirteen * J - 12  'loop thru columns with step thirteen           myArr(i, J) = Val(Mid$(Lines(i + fRow), k, 13)) 'Assign the value to the row/column "prison cell"        Next J     Next i     csvParser = myArr 'final transfer Finish Role

    Quote Originally Posted past dilettante View Post

    I'g a little mystified why yous'd want arrays with lower premises of one, but the demo deals with it anyhow.

    As we know to populate excel sheets from an array directly we have to ensure that we apply 2D arrays with lower premises of 1. Probably "0" bounds are reserved to fixed rows/columns of the excel filigree.

Posting Permissions

  • You may non post new threads
  • Yous may not post replies
  • Y'all may non postal service attachments
  • You lot may not edit your posts
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Click Here to Expand Forum to Full Width

davenportthews1968.blogspot.com

Source: https://www.vbforums.com/showthread.php?767349-RESOLVED-How-to-load-properly-a-text-file-in-an-array

Post a Comment for "Visual Vasic Studio Read Text File Into Array"