Results 1 to 27 of 27

Thread: Re: import text file to access table using vb

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    Re: import text file to access table using vb

    opss...please read the below detail.
    Last edited by gracehskuo; Jul 3rd, 2007 at 08:26 AM.

  2. #2

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    import text file to access table using vb

    hello,how to import text file to access table using vb?what i'm trying to do is import the text data from the select text file using commandialog select desire text file to import into the access database.i upload the text file here,the data want to import from text is only the value.please help.Thanks alot!


    this is the commondialog i done with!
    Code:
    Private Sub CmdSearch_Click()
    On Error GoTo ErrHandler
    
        With CommonDialog1
            .CancelError = True
            .Filter = "General Modules (*.txt)/*.txt"
            .ShowOpen
      End With   
       
    ErrHandler:
        Err.Clear
        Exit Sub
    
    End Sub
    Thanks for help!
    Attached Files Attached Files

  3. #3
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    I suggest you reinterpret the file as a CSV with column headers. You will have to parse the file anyway, its unavoidable.

    When you have the CSV, try the following query format

    INSERT INTO tablename (fieldslistdest) SELECT fieldslistsrc FROM tablesrc IN 'CSV path'

    sample

    INSERT INTO desttable (field_date, field_long, field_str) SELECT mydate, mylong, mystr FROM mysourcetable IN 'C:\sample\parsedCSV.txt'

    Where mydate, mylong, mystr are column header names you created for the CSV file. You then just have to execute the query on the connection object connected to the access database.

  4. #4

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    Re: import text file to access table using vb

    leinad31:
    hi,thanks your reply.i understand what you mean,but this HR software is only can export the data to txt File. for this way what to do next?

    Thanks for help!

  5. #5
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    Then read the txt file and create another textfile (the CSV). Then INSERT query the CSV to the access database.

    a) You'll have to parse the original text file anyway to ignore the extraneous text.
    b) You'll transfer the records as a batch rather than one record at a time.

  6. #6

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    Re: import text file to access table using vb

    leinad31,
    sorry this question abit silly ,how to create this "Then read the txt file and create another textfile (the CSV)."

    thanks for help!

  7. #7
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    What's the structure of the destination table (column names, data types, etc)? How do the table columns and the textfile data match?

  8. #8

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    Re: import text file to access table using vb

    ok,from the text file it may have the title header all that,but i just want to import the value to database table.The text file i only want to import is start from start and 1-3 column to the destination database fields StaffNo,StaffName,WorkTotalHours .
    StaffNo,StaffName datatype is Text
    WorkTotalHours datatype is Number

    Thanks for help!

  9. #9
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    Code:
    Option Explicit
    
    Private Sub Command1_Click()
    Dim iFileNum   As Integer
    Dim strText    As String
    Dim strArr()   As String
    Dim lIdx       As Long
    
    Dim strNo      As String
    Dim strName    As String
    Dim sngHrs     As Single
    
       iFileNum = FreeFile
       Open "C:\Temp\ATTEND TOTAL HOURS.TXT" For Input As #iFileNum
          strText = vbCrLf & Input(LOF(iFileNum), #iFileNum)
       Close #iFileNum
       
       strArr = Split(strText, vbCrLf & "   Dufu Industries Sdn Bhd") 'organize per page
       strText = ""   'reclaim memory
       For lIdx = 0 To UBound(strArr)   'Strip headers
          strArr(lIdx) = Mid$(strArr(lIdx), InStrRev(strArr(lIdx), "Leaves" & vbCrLf) + 8)
       Next
    
       strArr = Split(Join(strArr, ""), vbCrLf)  'reorganize per line
    
       iFileNum = FreeFile
       Open "C:\Temp\CSV.txt" For Output As #iFileNum
          Print #iFileNum, "StaffNo, StaffName,TotalHrs"  'print CSV column headers
          For lIdx = 0 To UBound(strArr) - 2
             strNo = Trim(Left$(strArr(lIdx), 10))
             strName = Trim(Mid$(strArr(lIdx), 11, 40))
             sngHrs = CSng(Mid$(strArr(lIdx), 51, 12))
             strText = Chr$(34) & strNo & Chr$(34) & ", " _
                & Chr$(34) & strName & Chr$(34) & ", " & Round(sngHrs, 2)
             Print #iFileNum, strText   'append to CSV
          Next
       Close #iFileNum
    End Sub

  10. #10

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    Re: import text file to access table using vb

    leinad31:
    thanks,the reinterpret text to csv file code is done. below is the import csv to the access database table.have error appear regarding the path of CSV.txt location is invalid.i been check the location i save the csv file is at d:\Attend\csv.txt . please help have a look for the strsql statement not sure i done the correct way.

    Code:
    Private Sub CmdImport_Click()
    Dim conDataConnection As Connection
    Dim strsql As String
    Dim Split_Data
    Dim Raw_Data As String
    
    'Create adatabase connection
      Set conDataConnection = New Connection
    
      conDataConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & App.Path & _
                             "\Attendance.mdb;Persist Security Info=False"
      
        'Open the source text file
        Open App.Path & "\CSV.txt" For Input As #1
            While Not EOF(1)
                Line Input #1, Raw_Data
                Split_Data = Split(Raw_Data, Chr(44), -1, vbTextCompare)
                strsql = "INSERT INTO TempA (field_StaffNo, field_StaffName, field_WorkTotalHours) SELECT StaffNo, StaffName, TotalHrs FROM mysourcetable IN 'D:\Attend\CVS.txt'"
                conDataConnection.Execute strsql
                DoEvents
            Wend
        Close
    conDataConnection.Close
    Set conDataConnection = Nothing
    
    End Sub
    thanks for help!
    Attached Images Attached Images  
    Last edited by gracehskuo; Jul 2nd, 2007 at 10:22 PM.

  11. #11
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    Yup. Let us know if there are errors.

  12. #12
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    Sorry the point of reference was wrong. Connect to the textfile using jet database engine and insert into access DB using IN clause.

    Code:
    Private Sub Command2_Click()
    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    
       Set conn = New ADODB.Connection
       conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
           "Data Source=c:\Temp\;" & _
           "Extended Properties=""text;HDR=Yes;FMT=Delimited"""
       conn.Execute "INSERT INTO DestTbl (StaffNo, StaffName, TotalHrs) IN 'C:\Temp\db1.mdb' " _
          & " SELECT StaffNo, StaffName, TotalHrs FROM CSV#TXT "
       conn.Close
       
       'see if records transferred
       conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
               "Data Source=C:\Temp\db1.mdb;"
       Set rs = conn.Execute("SELECT * FROM DestTbl ")
       Debug.Print rs.GetString(, , ", ", vbCrLf, "")
       rs.Close
       conn.Close
       
       Set rs = Nothing
       Set conn = Nothing
    End Sub
    No need to iterate through the CSV.
    Last edited by leinad31; Jul 3rd, 2007 at 12:54 AM.

  13. #13

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    Re: import text file to access table using vb

    leinad31:
    thanks ,basically the from cvs file import to table is done. sorry to disturb you regarding the text file reinterpret to csv file.if i want to add 2 field for date From and date To to the csv file,what should i edit from the statement?
    example:this is date is taken from the text file FROM 01/06/2007 TO 29/06/2007 ,i want this date from and date To ,save display at every after TotalHrs field.

    StaffNo, StaffName,TotalHrs ,DateFrom,DateTo
    "00004", "LIM BEE LENG", 0,1/06/07,29/6/07
    "00023", "YONG CHEE KHEONG", 0,1/06/07,29/6/07
    "00032", "HUI CHEE KING", 174.4,1/06/07,29/6/07
    "00037", "TAN WEI PENG", 199.17,1/06/07,29/6/07
    "00046", "YEOH CHOON HUAT", 190.87,1/06/07,29/6/07

    Code:
    Private Sub CmdConvert_Click()
    Dim iFileNum   As Integer
    Dim strText    As String
    Dim strArr()   As String
    Dim lIdx       As Long
    
    Dim strNo      As String
    Dim strName    As String
    Dim sngHrs     As Single
    
       iFileNum = FreeFile
       Open "D:\Attend\Temp\ATTEND TOTAL HOURS.TXT" For Input As #iFileNum
          strText = vbCrLf & Input(LOF(iFileNum), #iFileNum)
       Close #iFileNum
       
       strArr = Split(strText, vbCrLf & "   Dufu Industries Sdn Bhd") 'organize per page
       strText = ""   'reclaim memory
       For lIdx = 0 To UBound(strArr)   'Strip headers
          strArr(lIdx) = Mid$(strArr(lIdx), InStrRev(strArr(lIdx), "Leaves" & vbCrLf) + 8)
       Next
    
       strArr = Split(Join(strArr, ""), vbCrLf)  'reorganize per line
    
       iFileNum = FreeFile
       Open "D:\Attend\Temp\CSV.txt" For Output As #iFileNum
          Print #iFileNum, "StaffNo, StaffName,TotalHrs"  'print CSV column headers
          For lIdx = 0 To UBound(strArr) - 2
             strNo = Trim(Left$(strArr(lIdx), 10))
             strName = Trim(Mid$(strArr(lIdx), 11, 40))
             sngHrs = CSng(Mid$(strArr(lIdx), 51, 12))
             strText = Chr$(34) & strNo & Chr$(34) & ", " _
                & Chr$(34) & strName & Chr$(34) & ", " & Round(sngHrs, 2)
             Print #iFileNum, strText   'append to CSV
          Next
       Close #iFileNum
       
       MsgBox " Sucess Saved CSV File"
    End Sub
    Thanks for help!

  14. #14
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    After organizing per page and before the iteration which strips the header, extract the dates.

    Dim strFrom As String
    Dim strTo As String
    Dim lPos As Long

    lPos = InStr(1, strArr(0), " TO ")
    strFrom = Mid$(strArr(0), lPos - 10, 10)
    strTo = Mid$(strArr(0), lPos + 6, 10)

    Add the relevant columnsheaders in the CSV, and append to strText. You didn't mention the data type of date column in destination table (you will have to nest the date with # if datetime data type), and your date format may run into regional settings problems when you convert the date as string into date as datetime data type.

  15. #15

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    Re: import text file to access table using vb

    leinad31,
    hi,thanks you reply.i have try to added the code,but have error appear.

    Code:
    iFileNum = FreeFile
       Open "D:\Attend\Temp\CSV.txt" For Output As #iFileNum
          Print #iFileNum, "StaffNo, StaffName,TotalHrs,From,TO"  'print CSV column headers
          For lIdx = 0 To UBound(strArr) - 2
             strNo = Trim(Left$(strArr(lIdx), 10))
             strName = Trim(Mid$(strArr(lIdx), 11, 40))
             sngHrs = CSng(Mid$(strArr(lIdx), 51, 12))
             lPos = InStr(1, strArr(0), " TO ")
             strFrom = Mid$(strArr(0), lPos - 10, 10) 'error appear at this line
             strTo = Mid$(strArr(0), lPos + 6, 10)
             strText = Chr$(34) & strNo & Chr$(34) & ", " _
                & Chr$(34) & strName & Chr$(34) & ", " & Round(sngHrs, 2) & "," _
                & Chr$(34) & strFrom & Chr$(34) & "," & Chr$(34) & strTo & Chr$(34) & ""
             Print #iFileNum, strText   'append to CSV
          Next
       Close #iFileNum
    thanks for help!
    Attached Images Attached Images  
    Last edited by gracehskuo; Jul 3rd, 2007 at 08:27 AM.

  16. #16
    PowerPoster
    Join Date
    Feb 2006
    Location
    East of NYC, USA
    Posts
    5,691

    Re: import text file to access table using vb

    If LPos is less than 11, Mid$ is trying to start before the first character (character position LPos - 10). This could be due to " TO " being less than 11 characters from the start of strArr(0), or there's no " TO " in strArr(0) at all (giving you an LPos of 0).
    The most difficult part of developing a program is understanding the problem.
    The second most difficult part is deciding how you're going to solve the problem.
    Actually writing the program (translating your solution into some computer language) is the easiest part.

    Please indent your code and use [HIGHLIGHT="VB"] [/HIGHLIGHT] tags around it to make it easier to read.

    Please Help Us To Save Ana

  17. #17
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    Please refer to my previous post.

    I said the snippet comes just before iteration (first loop) and after organizing stream per page (the first split). Or between those two, I didn't say it goes in the second iteration.
    Last edited by leinad31; Jul 3rd, 2007 at 07:19 PM.

  18. #18

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    Re: import text file to access table using vb

    leinad31,
    hi,thanks you reply,i been refer back the previous post follow the step from your guide.but still have same error appear when excute the code.
    please help!

    Code:
    Private Sub CmdConvert_Click()
    Dim iFileNum   As Integer
    Dim strText    As String
    Dim strArr()   As String
    Dim lIdx       As Long
    Dim strNo      As String
    Dim strName    As String
    Dim sngHrs     As Single
    Dim strFrom As String
    Dim strTo As String
    Dim lPos As Long
    
       iFileNum = FreeFile
       Open "D:\Attend\Temp\ATTEND TOTAL HOURS.TXT" For Input As #iFileNum
          strText = vbCrLf & Input(LOF(iFileNum), #iFileNum)
       Close #iFileNum
       
       strArr = Split(strText, vbCrLf & "   Dufu Industries Sdn Bhd") 'organize per page
       strText = ""   'reclaim memory
       lPos = InStr(1, strArr(0), " TO ")
       strFrom = Mid$(strArr(0), lPos - 10, 10)'error still appear at this line
       strTo = Mid$(strArr(0), lPos + 6, 10)
       For lIdx = 0 To UBound(strArr)   'Strip headers
          strArr(lIdx) = Mid$(strArr(lIdx), InStrRev(strArr(lIdx), "Leaves" & vbCrLf) + 8)
       Next
    
       strArr = Split(Join(strArr, ""), vbCrLf)  'reorganize per line
       iFileNum = FreeFile
       Open "D:\Attend\Temp\CSV.txt" For Output As #iFileNum
          Print #iFileNum, "StaffNo, StaffName,TotalHrs,From,TO"  'print CSV column headers
          For lIdx = 0 To UBound(strArr) - 2
             strNo = Trim(Left$(strArr(lIdx), 10))
             strName = Trim(Mid$(strArr(lIdx), 11, 40))
             sngHrs = CSng(Mid$(strArr(lIdx), 51, 12))
             strText = Chr$(34) & strNo & Chr$(34) & ", " _
                & Chr$(34) & strName & Chr$(34) & ", " & Round(sngHrs, 2) & "," _
                & Chr$(34) & strFrom & Chr$(34) & "," & Chr$(34) & strTo & Chr$(34) & ""
             Print #iFileNum, strText   'append to CSV
          Next
       Close #iFileNum
       
       MsgBox " Sucess Saved CSV File"
    End Sub
    thanks for help!

  19. #19
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    That will only happen if the format of your source textfile is different or the string " TO " ins't in the header. You will have to parse the file differently if the format has changed.

  20. #20
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    BTW, it would be best to post the current source textfile so we can identify differences in format if there are any.

  21. #21

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    Re: import text file to access table using vb

    leinad31:
    thanks for your reply.i already post the current textfile here.please have a look.Thanks for help!
    Attached Files Attached Files
    Last edited by gracehskuo; Jul 4th, 2007 at 01:18 AM.

  22. #22
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    Ahh kk, my bad. Try index 1 or strArr(1).

  23. #23

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    Re: import text file to access table using vb

    leinad31:
    thanks your reply,the csv problem basically is done! now i have the imported csv to database error.sql syntax error appear.i refer back to the previous post you mention nest # for date data type.please help!

    Code:
      conn.Execute "INSERT INTO Attendance (StaffNo, StaffName, TotalHrs,#From) IN 'D:\Attend\Attendance.mdb' " _
          & " SELECT StaffNo, StaffName, TotalHrs,From FROM CSV#TXT "
       conn.Closesyntax error at this line
    thanks for help!

  24. #24
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    From is a reserved word, try using StartDate and EndDate for your column names.

  25. #25

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    Re: import text file to access table using vb

    leinad31:
    hi,basically csv file imported to database is done,thanks
    ok i have some question regarding the convert orginal textfile to csv file by using commondialog to select which by difference month of textfile to convert izzit possible to add in this?And for the import the csv file has been import to the database before,if import at second time it may have msgbox prompt out want to overwrite the existing data from database.sorry disturb agian,thanks for help!

  26. #26
    PowerPoster
    Join Date
    Nov 2002
    Location
    Manila
    Posts
    7,629

    Re: import text file to access table using vb

    Sorry kinda busy right now, will try to get back at you later. In case someone is free to look at the code, regarding existing records we'll look into modiying insert query to have pseudo

    INSERT INTO tbl (flds) IN 'access db path' SELECT B.flds FROM csv#txt AS B WHERE NOT EXISTS (SELECT staffno, startdate, enddate FROM tbl AS A IN 'access db path' WHERE A.staffno = B.staffno AND A.startdate = B.startdate AND A.enddate = B.enddate)

    If query is not possible, we'll look into creating a filtered csv.

  27. #27

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2006
    Posts
    584

    Re: import text file to access table using vb

    leinad31:
    hei guy,thanks alot!take your time.sorry to disturb you

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