Results 1 to 20 of 22

Thread: Help import from csv file

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #16
    Knowledge Base Approver VBAX Wizard p45cal's Avatar
    Joined
    Oct 2005
    Location
    Surrey UK
    Posts
    5,970
    A querytable can't overlap an Excel Table (listobject) and an empty table has at least two rows: header and empty data row.
    So all we can do is let it put the querytable where it wants to, then delete the querytable then extend the Excel Table, then delete all blank rows from the table:
    Sub Append_CSV_File()    ''working from vbaexpress.com
    Dim txtFileName As Variant
    Dim destCell As Range
    Dim qt
    Set destCell = Worksheets("TestingImport").Cells(Rows.Count, "B").End(xlUp).Offset(1)
    If destCell.Row < 9 Then Set destCell = Worksheets("TestingImport").Range("B9")
    
    txtFileName = Application.GetOpenFilename(FileFilter:="TXT Files (*.txt),*.txt", Title:="Select a TXT File", MultiSelect:=False)
    If txtFileName = False Then Exit Sub
        
    Set qt = destCell.Parent.QueryTables.Add(Connection:="TEXT;" & txtFileName, Destination:=destCell.Cells(1, 1))
    With qt
      .TextFileStartRow = 2    'this leaves the header away
      .TextFileParseType = xlDelimited
      .TextFileCommaDelimiter = False    'you might not need this line at all - it might even be better to make it False
      .TextFileOtherDelimiter = Empty
      .TextFileSemicolonDelimiter = True
      .RefreshStyle = xlOverwriteCells    '<<changed/added
      .Refresh BackgroundQuery:=False
      With Intersect(.ResultRange.EntireRow, .Parent.Range("S:S"))
        .ClearContents    '<<add
        .Cells(1) = 1
        .DataSeries Rowcol:=xlColumns, Type:=xlLinear, Date:=xlDay, Step:=1, Trend:=False
      End With
      Intersect(.ResultRange.EntireRow, .Parent.Range("A:A")).Value = "running"
      lr = .ResultRange.Rows(.ResultRange.Rows.Count).Row
      .WorkbookConnection.Delete
      .Delete
    End With
    With Worksheets("TestingImport").Range("B9").ListObject
      Set TL = .Range.Cells(1)
      lc = TL.Column + .ListColumns.Count - 1
      .Resize Range(TL, .Parent.Cells(lr, lc))
      'delete all blank rows in the table:
      For i = .ListRows.Count To 1 Step -1
        With .ListRows(i)
          If Application.CountA(.Range) = 0 Then .Delete
        End With
      Next i
    End With
    End Sub
    The attached has the code in a separate module rather than in the ThisWorkbook code-module.
    Attached Files Attached Files
    p45cal
    Everyone: If I've helped and you can't be bothered to acknowledge it, I can't be bothered to look at further posts from 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
  •