Results 1 to 21 of 21

Thread: Reading form text file (RESOLVED)

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Aug 2000
    Posts
    154

    Question Reading form text file (RESOLVED)

    Hey all,

    I am having trouble trying to read/write to/from a text file to/from multiple
    text boxes.

    What I would like to do is write each texbox to a seperate line in a text file
    like this...

    Text1 - line #1
    Text2 - line #2
    Text3 - line #3
    and so on...

    and then I would like to read each line into a different textbox, like this...

    line #1 - Text1
    line #2 - Text2
    line #3 - Text3


    Any help would be appreciated,
    Ron
    Last edited by rdcody; May 27th, 2005 at 04:58 PM.

  2. #2
    Frenzied Member sciguyryan's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,763

    Re: Reading form text file

    To read try something like this:

    VB Code:
    1. Dim intFree As Integer
    2. Dim strReadText As String
    3. Dim strTextLines() As String
    4. intFree = FreeFile
    5. Open "C:\SomeFile.txt" For Binary As #intFree
    6.     strReadText = Space$(LOF(intFree))
    7.     Get #intFree, , strReadText
    8. Close #intFree
    9. ' Create array of text lines from the file...
    10. strTextLines = Split(strReadText, vbNewLine)
    11.  
    12. Text1.Text = strTextLines(0) ' First line...
    13. Text2.Text = strTextLines(1) ' Second line...

    And to write try the follwoing...

    VB Code:
    1. Dim strMyText As String
    2. strMyText = Text1.text & vbNewLine & Text2.Text & vbNewLine & Text3.Text ' Etc.
    3.  
    4. Dim intFree As Integer
    5. intFree = FreeFile
    6. Open fileName For Binary Access Write As #intFree
    7.     Put #intFree, , strMyText
    8. Close #intFree

    Cheers,

    RyanJ
    My Blog.

    Ryan Jones.

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Aug 2000
    Posts
    154

    Re: Reading form text file

    Hey sciguyryan,

    Thanks for the quick reply.

    On this line...

    VB Code:
    1. strTextLines = Split(strReadText, vbNewLine)

    I get an "Can't assign to array" error. Any Ideas? By the way I'm using VB5.

    Thanks,
    Ron

  4. #4
    Frenzied Member sciguyryan's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,763

    Re: Reading form text file

    Quote Originally Posted by rdcody
    Hey sciguyryan,

    Thanks for the quick reply.

    On this line...

    VB Code:
    1. strTextLines = Split(strReadText, vbNewLine)

    I get an "Can't assign to array" error. Any Ideas? By the way I'm using VB5.

    Thanks,
    Ron
    Hmm, I am afraid I do not use VB5 and so, am unable to test that....

    I'll see if I can check if it can be done that way in VB5

    Cheers,

    RyanJ
    My Blog.

    Ryan Jones.

  5. #5
    Admodistrator |2eM!x's Avatar
    Join Date
    Jan 2005
    Posts
    3,900

    Re: Reading form text file

    check the codebank, posted by manavo like 5 days ago

  6. #6
    Frenzied Member sciguyryan's Avatar
    Join Date
    Sep 2003
    Location
    Wales
    Posts
    1,763

    Re: Reading form text file

    Quote Originally Posted by |2eM!x
    check the codebank, posted by manavo like 5 days ago
    ARGH! Damn my memory... Its not my fault - I blame the exams

    Thanks for that - I wound have been here for hours looking otherwise

    Cheers,

    RyanJ
    My Blog.

    Ryan Jones.

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Aug 2000
    Posts
    154

    Re: Reading form text file

    Well...I'll be damned if I can find it...

  8. #8

    Thread Starter
    Addicted Member
    Join Date
    Aug 2000
    Posts
    154

    Re: Reading form text file

    Are you guys talking about the split function by manavo11? I have that,
    but I still get the same error. Any ideas?

  9. #9
    Member seraphicmortal's Avatar
    Join Date
    May 2005
    Posts
    56

    Smile Re: Reading form text file

    Hi RD Cody! I had that kind of program as well.. why don't you give this a try.. These codes saves the text being inputted by the user in the textbox in a file (which the file extension can btw be specified by you) and the user can retrieve the file and show the same text and order back to the form where your textboxes are... Quite a long explanation eyh.. You can tweek it to suit your needs if you want.

    I made a class, which I named namelist.
    This class has properties namely:
    name
    symbol
    quantity

    My example.plp output would look like this when opened in a text editor(like notepad):
    [Name] x32
    [Quantity] x75
    [Symbol] q21


    (globalvar.bas)
    VB Code:
    1. Option Explicit
    2.  
    3. Public pl1 As New namelist

    (frm_field) 'This is the form where the textboxes are
    VB Code:
    1. Option Explicit
    2.  
    3. Private Sub fieldupload()
    4.     With pl1
    5.         .symbol = txt_sym.Text
    6.         .name = txt_name.Text
    7.         .quantity = txt_qty.Text
    8.     End With
    9. End Sub
    10.  
    11. Private Sub cmd_apply_Click()
    12.     If Len(txt_sym.Text) = 0 Or _
    13.        Len(txt_name.Text) = 0 Or _
    14.        Len(txt_qty.Text) = 0 Or _
    15.         MsgBox "please enter the necessary values."
    16.         txt_sym.SetFocus
    17.     Else
    18.         fieldupload
    19.         MsgBox ("Creating profile...  Please choose what directory to save your profile.")
    20.         frm_dir.Caption = "Save Profile"
    21.         frm_dir.Show vbModal
    22.     End If
    23. End Sub
    24.  
    25. Function GetString(tmpStr As String, tmpDiv As String, Mode As String) As String
    26. Dim tmpRetStr As String
    27. Dim tmpLen As Integer
    28. Dim tmpErr As Integer
    29.   ' *****************************************************
    30.   ' tmpString = The whole string
    31.   ' tmpDiv = The Divider chr
    32.   ' if mode = "F" then get the string in front of the div
    33.   '
    34.   ' Return values:
    35.   '  Errors
    36.   '    Err1 = wrong mode
    37.   '    Err2 =  No Div, did not found a divider
    38.   '    Err5 = No String
    39.   '    Err6 = No C, did not find any string in the middle
    40.   '  Normal
    41.   '    String
    42.   ' ******************************************************
    43.   ' Example: GetString("Red=Green","=","F") will retrun "Red"
    44.   ' *** for string
    45.   tmpErr = 0
    46.   If Len(tmpStr) = 0 Then
    47.     tmpErr = 5
    48.     GoTo GetStringErr
    49.   End If
    50.  
    51.   ' *** test for chr in tmpDiv
    52.   If Len(tmpDiv) = 0 Then
    53.     tmpErr = 2
    54.     GoTo GetStringErr
    55.   End If
    56.  
    57.   ' *** test for div in string
    58.   If InStr(1, tmpStr, tmpDiv) = 0 Then
    59.     tmpErr = 2
    60.     GoTo GetStringErr
    61.   End If
    62.  
    63.   If Mode = "C" Then
    64.      tmpRetStr = Mid(tmpStr, 9)
    65.      If Len(tmpRetStr) > 0 Then
    66.          GetString = tmpRetStr
    67.          Exit Function
    68.      Else
    69.          tmpErr = 6
    70.          'GoTo GetStringErr
    71.          MsgBox ("Error: Non-standard format in saving profile name.  No hyphen '-' found.")
    72.          frm_dir.txt_plprofile.Text = "*.plp"
    73.      End If
    74.          MsgBox ("Error: Non-standard format in saving profile name.  No hyphen '-' found.")
    75.          frm_dir.txt_plprofile.Text = "*.plp"
    76.   End If
    77.  
    78.     tmpErr = 1
    79.     frm_dir.txt_plprofile.Text = "*.plp"
    80.     'GoTo GetStringErr
    81.   Exit Function
    82. GetStringErr:
    83. GetString = "Err" & tmpErr
    84. End Function
    85.  
    86.  
    87. Private Sub loadfield()
    88.     txt_sym.Text = pl1.symbol
    89.     txt_name.Text = pl1.name
    90.     txt_qty.Text = pl1.quantity
    91. End Sub
    92.    
    93. Private Sub cmd_back_Click()
    94.     Form_Load
    95.     Me.Hide
    96.     frm_loadfile.Show vbModal
    97. End Sub
    98.  
    99. Private Sub cmd_next_Click()
    100.     Me.Hide
    101.     frm_summary.Show vbModal ' another form which basically are just labels that shows a summmay of the information
    102. End Sub
    103.  
    104. Private Sub cmd_retrieve_Click()
    105.     frm_dir.file1.Enabled = True
    106.     loadfield
    107.    
    108.     frm_dir.Caption = "Load Profile"
    109.     frm_dir.Show vbModal
    110. End Sub
    111.  
    112. Private Sub Form_Load()
    113. On Error GoTo Form_Load_Error
    114. 'This code sets up the Text Boxes
    115.     cmd_next.Enabled = False
    116.     Me.txt_name.Text = ""
    117.     Me.txt_qty.Text = ""
    118.     Me.txt_sym.Text = ""
    119. On Error GoTo 0
    120. Exit Sub
    121.  
    122. Form_Load_Error:
    123. MsgBox "Error " & Err.Number & " (" & Err.description & ") in procedure Form_Load of Form " & Me.Name
    124. End Sub
    125.  
    126. Private Sub Validate_Entry(ByRef txtBox As TextBox)
    127.  
    128.     If Left$(txtBox.Text, 1) <> vbNullString Then
    129.         If UCase(txtBox.Text) Like "[A-Z]" & String(Len(txtBox.Text) - 1, "#") And Len(txtBox.Text) < 6 Then
    130.             txtBox.Text = UCase(txtBox.Text)
    131.             txtBox.SelStart = Len(txtBox.Text)
    132.         Else
    133.             MsgBox "Please try again.", vbOKOnly + vbInformation, "Invalid Entry"
    134.             txtBox.Text = ""
    135.         End If
    136.     End If
    137. End Sub
    138.  
    139. Private Sub txt_qty_Change()
    140.     Call Validate_Entry(txt_qty)
    141. End Sub
    142.  
    143. Private Sub txt_sym_Change()
    144.     Call Validate_Entry(txt_sym)
    145. End Sub
    146.  
    147. Private Sub txt_name_Change()
    148.     Call Validate_Entry(txt_name)
    149. End Sub

    now to save the text inputted in the textbox in a file....use this
    (frm_dir)

    VB Code:
    1. Option Explicit
    2. Public profilepath As String
    3. Public finalprofile As String
    4.  
    5. Private Sub Form_Load()
    6. Dim prof As String
    7.     txt_profilepath.Enabled = False
    8.     file1.Enabled = False
    9.     txt_plprofile.Text = frm_loadfile.var1
    10.     prof = frm_field.GetString(txt_plprofile.Text, "-", "C")
    11.     txt_plprofile.Text = prof + ".plp"
    12.      'txt_plprofile.Text = prof + ".plp"
    13. End Sub
    14.  
    15. Private Sub cmd_cancel_Click()
    16.     MsgBox "Cancelled"
    17.     Unload Me
    18. End Sub
    19.  
    20. Private Sub cmd_ok_Click()
    21. Dim prof As String
    22.  
    23. Select Case Me.Caption
    24.     Case "Save Profile"
    25.     txt_profilepath.Text = file1.Path & "\" & file1.FileName & txt_plprofile.Text
    26.         If isFile(txt_profilepath.Text) Then
    27.             txt_plprofile.Text = frm_loadfile.var1
    28.             prof = frm_field.GetString(txt_plprofile.Text, "-", "C")
    29.                 If MsgBox("File " & txt_profilepath & " exists.  Do you want to overwrite the current profile?{Y/N]", vbQuestion + vbYesNo, App.ProductName + " Prompt") = vbYes Then
    30.                     SaveProfile txt_profilepath.Text, pl1
    31.                     finalprofile = txt_plprofile.Text
    32.                 Else
    33.                     txt_profilepath.Text = file1.Path & file1.FileName & "\" & prof & Format(Now, "mmddyyyyhhmmss") & ".plp"
    34.                     SaveProfile txt_profilepath.Text, pl1
    35.                     finalprofile = txt_plprofile.Text
    36.                 End If
    37.         Else
    38.             MsgBox "Saving " & txt_profilepath & " as new profile."
    39.             SaveProfile txt_profilepath.Text, pl1
    40.             finalprofile = txt_plprofile.Text
    41.         End If
    42.  
    43.         profilepath = txt_profilepath.Text
    44.         frm_field.cmd_next.Enabled = True
    45.  
    46.     Case "Load Profile"
    47.         txt_profilepath.Text = file1.Path & "\" & file1.FileName
    48.         MsgBox "Loading " & txt_profilepath & " profile."
    49.             LoadProfile txt_profilepath.Text, pl1
    50.         profilepath = txt_profilepath.Text
    51.         frm_field.cmd_next.Enabled = True
    52. End Select
    53.     Me.Hide
    54. End Sub
    55.  
    56. Private Sub LoadProfile(WhatFile As String, TheProfile As partslist)
    57. Dim FreeFileHandle  As Integer, a$, B() As String
    58.  
    59.     FreeFileHandle = FreeFile
    60.     Open WhatFile For Input As FreeFileHandle
    61.     With TheProfile
    62.         Line Input #FreeFileHandle, a ' "[Symbol] " & .symbol
    63.         B = Split(a, " ")
    64.         .symbol = B(1)
    65.         frm_field.txt_sym.Text = .symbolic
    66.        
    67.         Line Input #FreeFileHandle, a ' "[Name] " & .Name
    68.         B = Split(a, " ")
    69.         .name = B(1)
    70.         frm_field.txt_name.Text = .name
    71.        
    72.         Line Input #FreeFileHandle, a '  "[Quantity] " & .quantity
    73.         B = Split(a, " ")
    74.         .quantity = B(1)
    75.         frm_field.txt_qty.Text = .quantity
    76.  
    77.     End With
    78.     Close FreeFileHandle
    79. End Sub
    80.  
    81.  
    82. Private Sub SaveProfile(WhatFile As String, TheProfile As namelist)
    83. Dim FreeFileHandle  As Integer
    84.  
    85.     FreeFileHandle = FreeFile
    86.     Open WhatFile For Output As FreeFileHandle
    87.     With TheProfile
    88.         Print #FreeFileHandle, "[Name] " & .name
    89.         Print #FreeFileHandle, "[Quantity] " & .quantity
    90.         Print #FreeFileHandle, "[Symbolic] " & .symbol
    91.     End With
    92.     Close FreeFileHandle
    93. End Sub
    94.  
    95. Private Sub dir1_Change()
    96.     file1.Path = dir1.Path
    97. End Sub
    98.  
    99. Private Sub drive1_Change()
    100.     dir1.Path = drive1.Drive
    101. End Sub
    102.  
    103. Private Sub file1_PathChange()
    104.     Me.Caption = "Dialog Box - [" & file1.Path & "]"
    105. End Sub
    106.  
    107. Private Sub file1_Click()
    108.     txt_plprofile.Text = file1.FileName 'file1 is a file list box
    109. End Sub
    110.  
    111. Function isFile(ByVal sFileName As String) As Integer
    112.   On Error Resume Next
    113.   Dim lFileLength As Long
    114.   Const ATTR_NORMAL = 0
    115.  
    116.   isFile = False
    117.   If Dir$(sFileName, ATTR_NORMAL) <> "" Then
    118.   lFileLength = FileLen(sFileName)
    119.   If (lFileLength > 0) Then isFile = True
    120.   End If
    121. End Function


    I hope this helps..
    Yoroshiku,
    seraphicmortal


    ______________________________________________________
    Thirst for knowledge can never be quenched...Ask for more!!.


    Oh! Please..Show your appreciation by clicking if you deem this post helpful.
    Rate this Post!

  10. #10
    Member seraphicmortal's Avatar
    Join Date
    May 2005
    Posts
    56

    Cool Re: Reading form text file

    The codes above btw came not only from me but with the help of our buds from vbforum.. (Baja and Joacim)

    You can go here to view my thread...
    http://www.vbforums.com/showthread.php?t=339887
    Yoroshiku,
    seraphicmortal


    ______________________________________________________
    Thirst for knowledge can never be quenched...Ask for more!!.


    Oh! Please..Show your appreciation by clicking if you deem this post helpful.
    Rate this Post!

  11. #11

    Thread Starter
    Addicted Member
    Join Date
    Aug 2000
    Posts
    154

    Re: Reading form text file

    Thanks for the reply, but I'm still having trouble with the Split function. I'm
    going to have to find a different way of doing this.

  12. #12
    Member seraphicmortal's Avatar
    Join Date
    May 2005
    Posts
    56

    Question Re: Reading form text file

    mind expounding why you're having trouble using Split function?
    Yoroshiku,
    seraphicmortal


    ______________________________________________________
    Thirst for knowledge can never be quenched...Ask for more!!.


    Oh! Please..Show your appreciation by clicking if you deem this post helpful.
    Rate this Post!

  13. #13

    Thread Starter
    Addicted Member
    Join Date
    Aug 2000
    Posts
    154

    Re: Reading form text file

    I use VB5, and the Split function that manavo11 supplied just doesn't seem
    to work.

  14. #14
    Guru Aaron Young's Avatar
    Join Date
    Jun 1999
    Location
    Red Wing, MN, USA
    Posts
    2,177

    Re: Reading form text file

    Try:
    VB Code:
    1. Private Function SplitEx(ByVal sString As String, Optional ByVal sDelim As String = " ") As Variant
    2.     Dim sItem As String
    3.     Dim sList() As String
    4.     Dim lChar As Long
    5.     Dim lCount As Long
    6.    
    7.     Do
    8.       ' Reset Split for non-Quoted Values
    9.       lChar = InStr(sString, sDelim)
    10.        
    11.       If lChar > 0 Then
    12.           ' Extract the Item from the String
    13.           sItem = Left(sString, lChar - 1)
    14.           ' Remove Item from the Remaining String
    15.           sString = Mid(sString, lChar + Len(sDelim))
    16.       Else
    17.           ' Remaining String, becomes final Item
    18.           sItem = sString
    19.           sString = ""
    20.       End If
    21.        
    22.       ' If something was extracted, add it to the Array
    23.       If Len(sItem) > 0 Then
    24.           ReDim Preserve sList(lCount)
    25.           sList(lCount) = sItem
    26.           lCount = lCount + 1
    27.       End If
    28.        
    29.     ' Continue until no more delimiters are found.
    30.     Loop While lChar > 0
    31.    
    32.     ' If there were items, return the array
    33.     If lCount > 0 Then
    34.         SplitEx = sList
    35.     Else
    36.         ' Otherwise return an empty array
    37.         SplitEx = Array()
    38.     End If
    39. End Function
    40.  
    41. Private Sub Command1_Click()
    42.    Dim intFree As Integer
    43.    Dim strReadText As String
    44.    Dim strTextLines() As String
    45.    
    46.    intFree = FreeFile
    47.    Open "C:\SomeFile.txt" For Binary As #intFree
    48.        strReadText = Space$(LOF(intFree))
    49.        Get #intFree, , strReadText
    50.    Close #intFree
    51.    
    52.    ' Create array of text lines from the file...
    53.    strTextLines = SplitEx(strReadText, vbNewLine)
    54.    
    55.    Text1.Text = strTextLines(0) ' First line...
    56.    Text2.Text = strTextLines(1) ' Second line...
    57. End Sub
    Regards,

    - Aaron.

  15. #15

    Thread Starter
    Addicted Member
    Join Date
    Aug 2000
    Posts
    154

    Re: Reading form text file

    Hey Aaron,

    I'm still getting the same error...

    VB Code:
    1. [B]strTextLines =[/B] SplitEx(strReadText, vbNewLine)

    Compile error: "Can't assign to array"

    I don't know...I'm about to give up.

  16. #16
    Hyperactive Member
    Join Date
    May 2005
    Posts
    258

    Re: Reading form text file

    I run VB6 at work and had that same problem the other day. The reason you get that array error when using the split function is because split turns the variable into an array using a delimiter to make distinctions between elements. An example is:


    dim fso as FileSystemObject
    dim myTextStream as TextStream
    dim myReadText() as String

    set fso = New FileSystemObject

    set myTextStream = fso.OpenTextFile("C:\File.txt")

    myReadText = Split(myTextStream.ReadLine, "|") 'The "pipe" symbol is the divider of the text
    MsgBox (myReadText(0))
    MsgBox (myReadText(1))
    MsgBox (myReadText(2))



    This is just an example. The split function turns the variable into an array. So make sure you dim that variable accordingly.


    I hope this helps.

  17. #17

    Thread Starter
    Addicted Member
    Join Date
    Aug 2000
    Posts
    154

    Re: Reading form text file

    Well...I don't know...this is above my head. Isn't everything declared properly?

  18. #18
    Hyperactive Member
    Join Date
    May 2005
    Posts
    258

    Re: Reading form text file

    Try defining a delimiter like I did, instead of vbNewLine. It may be that VB 5 doesn't have that command, I think that is a .NET upgrade.

  19. #19
    Guru Aaron Young's Avatar
    Join Date
    Jun 1999
    Location
    Red Wing, MN, USA
    Posts
    2,177

    Re: Reading form text file

    Try changing "strTextLines" to a Variant data type instead of a String array, i.e.
    VB Code:
    1. Private Sub Command1_Click()
    2. Dim intFree As Integer
    3. Dim strReadText As String
    4. 'Dim strTextLines() As String
    5. Dim strTextLines As Variant
    6.  
    7. intFree = FreeFile
    8. Open "C:\SomeFile.txt" For Binary As #intFree
    9.     strReadText = Space$(LOF(intFree))
    10.     Get #intFree, , strReadText
    11. Close #intFree
    12.  
    13. ' Create array of text lines from the file...
    14. strTextLines = SplitEx(strReadText, vbNewLine)
    15.  
    16. Text1.Text = strTextLines(0) ' First line...
    17. Text2.Text = strTextLines(1) ' Second line...
    18. End Sub
    Regards,

    - Aaron.

  20. #20
    Fanatic Member space_monkey's Avatar
    Join Date
    Apr 2005
    Location
    神と歩くこと
    Posts
    573

    Re: Reading form text file

    I'm kinda new and don't really know too much but If you want to avoid the split, you can simply open the file a different way.

    VB Code:
    1. dim strArray(0 to NUMOFTXTBOXES -1) as string
    2. dim i as long
    3. dim FileHandle%
    4. dim strFileName as string
    5.  
    6. FileHandle% = FreeFile
    7. i = 0
    8.  
    9. Open strFileName For Input As #FileHandle%
    10.     Do While Not EOF(FileHandle%)
    11.         Line Input #FileHandle%, strArray(i)
    12.         i = i+1
    13.     Loop
    14.  
    15.  
    16. textbox0 = strArray(0)
    17. textbox1 = strArray(1)
    18. ...
    19. textboxN = strArray(N)
    20.  
    21.  
    22.  
    23. Close FileHandle%


    HTH
    Last edited by space_monkey; May 27th, 2005 at 03:47 PM. Reason: Cause I'm a little slow late in the afternoon especially on a friday
    Using VB6 or VB.net 2008 with .net 3.5
    "Life... death... either way I'll be confined to a small cubicle!" - Hermes Conrad

  21. #21

    Thread Starter
    Addicted Member
    Join Date
    Aug 2000
    Posts
    154

    Re: Reading form text file

    OK...here are the results...

    To tacoman667...I tried that, and it didn't make any difference.

    To Aaron...That worked...except if you enter a blank line in the file, then I
    get a "subscript out of range" error. In other words, there are 6 lines of
    text (2 blank), and when it puts them into the 6 textboxes, it uses the first
    four, and then I get the error.

    To space_monkey...it worked perfectly!

    I want to thank all you guys for helping to figure this out,
    Ron

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width