Results 1 to 7 of 7

Thread: [RESOLVED] Problem saving a csv file to mdb..

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jun 2004
    Location
    cainta
    Posts
    80

    Resolved [RESOLVED] Problem saving a csv file to mdb..

    Hi All,

    My objective is to open a .csv file (with out field name) and save to .mdb (with field name) i've created. My problem is the csv file doesn't have any field name to select and supposedly assign to mdb fields.

    Csv file;
    A 1 jon ax 3 4 5 8 9 0 1 3
    B 5 bell 7 8 6 9 7 8
    C 9 ton ax 0 4 4

    Mdb filed name;
    set no. name A B C D E F G H I

    I can open the csv file but saving the content inside the mdb is my problem..
    I am usign VB.. Hoping to hear from you soon..

    Many Thanks!

  2. #2

  3. #3
    Junior Member
    Join Date
    Aug 2009
    Posts
    21

    Re: Problem saving a csv file to mdb..

    Chowking,

    CSV files are simply tab-delimited text files. You would need to "parse" the file either first, or as you go. That is, you will need to separate the fields and assign them to variables. If you work with the fields a lot, you might consider creating a datatype. Once you have a line parsed you will need to append a record to your database. To do this you will need a statement something like this:

    Code:
    Sql = "INSERT INTO PluInfo ( PluRef, [Desc], Retail, Cost, LastCost, InvAv, "
    Sql = Sql & "Taxable, Mfg, QOH, ReordBelow, DefaultVendor, TaxRate, Discountable, "
    Sql = Sql & "NormReord, MinReord, LastMod, Status )  "
    Sql = Sql & " SELECT "
    Sql = Sql & NewPlu.PluRef & ", "
    Sql = Sql & Chr(34) & Trim(NewPlu.Desc) & Chr(34) & ", "
    Sql = Sql & NewPlu.Retail & ", "
    Sql = Sql & NewPlu.Cost & ", "
    Sql = Sql & NewPlu.LastCost & ", "
    Sql = Sql & "0, "                           'InvAvg = 0
    Sql = Sql & NewPlu.Taxable & ", "
    Sql = Sql & NewPlu.Mfg & ", "
    Sql = Sql & 0 & ", "                        'QOH = 0
    Sql = Sql & NewPlu.ReOrdBelow & ", "
    Sql = Sql & NewPlu.DefaultVendor & ", "
    Sql = Sql & NewPlu.TaxRate & ", "
    Sql = Sql & NewPlu.Discountable & ", "
    Sql = Sql & NewPlu.NormReord & ", "
    Sql = Sql & NewPlu.MinReord & ", "
    Sql = Sql & "#" & Now() & "#, "
    If NewPlu.Status < 1 Then
        Sql = Sql & "1; "
    Else
        Sql = Sql & NewPlu.Status & ";"
    End If
    
    Db.Execute Sql
    This presumes that you have opened your database.

    Parsing your csv into lines and then parsing each line into fields is the way I generally handle this. You can use a function like this:

    Code:
    Public Function ParseLines(Txt As String, Separator As String) As String()
        Dim iBeg As Long
        Dim iEnd As Long
        Dim iLen As Long
        Dim S() As String
        Dim Cnt As Long
        Dim L() As String
        Dim X As Long
    
        ReDim S(100)
        
        iBeg = 1
        
        Txt = Trim(Txt)
        Do
            iEnd = InStr(iBeg, Txt, Separator)
            iLen = iEnd - iBeg
            If iLen < 0 Then
                Exit Do
            End If
            S(Cnt) = Mid(Txt, iBeg, iLen)
            iBeg = iEnd + Len(Separator)
            Cnt = Cnt + 1
            If Cnt > UBound(S) Then
                ReDim Preserve S(Cnt + 500)
            End If
        Loop Until iBeg > Len(Txt)
        S(Cnt) = Mid(Txt, iBeg, (Len(Txt) - iBeg) + 1)
        
        If Len(S(Cnt)) > 0 Then
            Cnt = Cnt + 1
        End If
        
        ReDim L(Cnt - 1)
            
        For X = 0 To Cnt - 1
            L(X) = S(X)
        Next X
        
        ParseLines = L
        
    End Function
    To parse the csv file into lines you would do this:

    Code:
    Dim CSV as String
    Dim L() as String
    Dim F() as String
    Dim X as Integer
    
    CSV = GetCSVTxt         'I am Assuming you have some function that does this
    
    L = ParseLines(CSV,VBCrLf)
    
    For X = 0 to ubound(L)
         F = ParseLines(L(x))
         'F is now an array of the Fields For Line X
         'You Would then add a call to a function to save this record to the DataBase
    Next X
    Hope this helps

    Fish

  4. #4
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: Problem saving a csv file to mdb..

    I don't have vb6 only vba (I am in office ) now so doing it offhand... Please amend syntax errors, if any.

    vb Code:
    1. Private Sub Command1_Click()
    2.     Dim oAccss As Access.Application
    3.  
    4.     Set oAccss = New Access.Application
    5.    
    6.     '~~> Change this to your relevant file
    7.     oAccss.OpenCurrentDatabase "c:\MyDatabase.mdb"
    8.    
    9.     '~~> Do the transfer
    10.     oAccss.DoCmd.TransferText acImportDelim, _
    11.     , "Table1", "c:\MyCsv.csv", True
    12.    
    13.     '~~> Close and Cleanup
    14.     oAccss.CloseCurrentDatabase
    15.     Set oAccss = Nothing
    16. End Sub
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  5. #5
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,709

    Re: Problem saving a csv file to mdb..

    You should have some error handling in case Access isnt installed or available on the users system too as well as make it a bit more dynamic with a commondialog control.

    Bored at work and its lunch time

    Code:
    Option Explicit
    'Add a reference to Microsoft Access xx.0 Object Library
    Private moApp As Access.Application
    
    Private Sub Command1_Click()
        On Error GoTo My_Error
    
        'Create object only if it doesnt exist
        If TypeName(moApp) = "Nothing" Then
            Set moApp = CreateObject("Access.Application")
        End If
        'No need to show Access database
        moApp.Visible = False
        With CommonDialog1
            .CancelError = True
            .Filter = "Microsoft Access 1997-2003 Database (*.mdb)|*.mdb|Microsoft Access 2007 Database (*.accdb)|*.accdb"
            .FilterIndex = 1
            .FileName = vbNullString
            .Flags = cdlOFNFileMustExist Or cdlOFNPathMustExist
            .ShowOpen
            If .FileName <> vbNullString Then
                 moApp.OpenCurrentDatabase .FileName
            Else
                Exit Sub
            End If
        End With
        'Turn off warning messages like "Macros" etc.
        moApp.DoCmd.SetWarnings False
        'Do the actual import. Maybe add a checkbox in your
        'app to identify if it has first row with field names
        'or if you have a saved import specification to use
        With CommonDialog1
            .CancelError = True
            .Filter = "Comma Delimited Files Only (*.csv)|*.csv"
            .FilterIndex = 1
            .FileName = vbNullString
            .Flags = cdlOFNFileMustExist Or cdlOFNPathMustExist
            .DialogTitle = "Select CSV File To Import"
            .ShowOpen
            If .FileName <> vbNullString Then
                moApp.DoCmd.TransferText acImportDelim, , "Table1", .FileName, False
            Else
                'They clicked Cancel
                Exit Sub
            End If
        End With
        'Return the warnings back
        moApp.DoCmd.SetWarnings True
        Exit Sub
    My_Error:
        If Err.Number <> cdlCancel Then
            MsgBox Err.Number & " - " & Err.Description, vbOKOnly + vbExclamation
        End If
    End Sub
    
    Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
        On Error GoTo My_Error
        'Clean up objects in memory
        If TypeName(moApp) <> "Nothing" Then
            moApp.CloseCurrentDatabase
            moApp.Quit acQuitSaveNone
        End If
        Set moApp = Nothing
        Exit Sub
        
    My_Error:
        Set moApp = Nothing
    End Sub
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

  6. #6

    Thread Starter
    Lively Member
    Join Date
    Jun 2004
    Location
    cainta
    Posts
    80

    Re: Problem saving a csv file to mdb..

    Well appreciated! Thank you so much!

  7. #7
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,709

    Re: Problem saving a csv file to mdb..

    No prob, glad to help.

    Ps,, if all your questions have been answered on this topic, please dont forget to mark your thread as Resolved so others know its done.
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

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