Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Macro to import multiple TXT files (without column headings) from a fixed directory into a single worksheet

Posted on 2009-07-15
2
Medium Priority
?
572 Views
Last Modified: 2012-06-27
Please reference the original question in the "Related Solution" link (http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_24032194.html)

RobSampson provided the attached code in an earlier question and it works great to import multiple .txt files into a single Excel workbook. However, It appears that this code expects column headings in the source files to work properly. The first file in the list is imported in its entirety but subsequent files have the first row omitted. How can I modify the code to work with source files without column headings.

Thanks for your help!
David

My data does not have column headings.

Private Declare Function SetCurrentDirectoryA Lib _
            "kernel32" (ByVal lpPathName As String) As Long
 
Public Function ChDirNet(szPath As String) As Boolean
'based on Rob Bovey's code
    Dim lReturn As Long
    lReturn = SetCurrentDirectoryA(szPath)
    ChDirNet = CBool(lReturn <> 0)
End Function
 
 
Sub Get_CSV_Files_To_One_WB()
'For Excel 2000 and higher
    Dim Fnum As Long
    Dim mybook As Workbook
    Dim basebook As Workbook
    Dim CSVFileNames As Variant
    Dim SaveDriveDir As String
    Dim ExistFolder As Boolean
 
    'Save the current dir
    SaveDriveDir = CurDir
 
    'You can change the start folder if you want for
    'GetOpenFilename,you can use a network or local folder.
    'For example ChDirNet("C:\Users\Ron\test")
    'It now use Excel's Default File Path
 
    ExistFolder = ChDirNet(Application.DefaultFilePath)
    If ExistFolder = False Then
        MsgBox "Error changing folder"
        Exit Sub
    End If
 
    ' Make sure all cells are "Text" format before import
    Cells.NumberFormat = "@"
    Range("A1").Select
    
    ' Get user to select the file(s)
    'CSVFileNames = Application.GetOpenFilename _
    '    (filefilter:="CSV Files (*.csv), *.csv", MultiSelect:=True)
    CSVFileNames = Application.GetOpenFilename _
        (filefilter:="TXT Files (*.txt), *.txt", MultiSelect:=True)
        
    If IsArray(CSVFileNames) Then
 
        On Error GoTo CleanUp
 
        With Application
            '.ScreenUpdating = False
            .EnableEvents = False
        End With
 
        'Add workbook with one sheet
        'Set basebook = Workbooks.Add(xlWBATWorksheet)
        Set basebook = ActiveWorkbook
        
        'Delete all sheets except the first sheet of basebook
        On Error Resume Next
        Application.DisplayAlerts = False
        While basebook.Sheets.Count > 1
            basebook.Worksheets(basebook.Worksheets.Count).Delete
        Wend
        Application.DisplayAlerts = True
        On Error GoTo 0
        
        'Loop through the array with csv files
        For Fnum = LBound(CSVFileNames) To UBound(CSVFileNames)
 
            'Set mybook = Workbooks.Open(CSVFileNames(Fnum))
            Workbooks.OpenText Filename:= _
               CSVFileNames(Fnum), Origin:=437, StartRow:= _
               1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
               ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, Comma:=True _
               , Space:=False, Other:=False, FieldInfo:=Array(Array(1, 2), Array(2, 2), _
               Array(3, 2), Array(4, 2), Array(5, 2), Array(6, 2), Array(7, 2), Array(8, 2), _
               Array(9, 2), Array(10, 2), Array(11, 2), Array(12, 2), Array(13, 2), Array(14, 2), _
               Array(15, 2)), TrailingMinusNumbers:=True
            
            Set mybook = ActiveWorkbook
 
            intLastRow = mybook.Worksheets(1).Cells(65536, 1).End(xlUp).Row
            intLastCol = mybook.Worksheets(1).Cells(1, 256).End(xlToLeft).Column
            intLastBaseRow = basebook.Sheets(1).Cells(65536, 1).End(xlUp).Row
            If intLastBaseRow > 1 Then
                intLastBaseRow = intLastBaseRow + 1
                intFirstRow = 2
            Else
                intFirstRow = 1
            End If
            mybook.Worksheets(1).Range(Cells(intFirstRow, 1).Address & ":" & Cells(intLastRow, intLastCol).Address).Copy _
                basebook.Sheets(1).Cells(intLastBaseRow, "A")
 
            mybook.Close savechanges:=False
 
        Next Fnum
  
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
        End With
        
        basebook.Sheets(1).Select
        basebook.Sheets(1).Cells(1, "A").Select
        
        MsgBox "Please save this save the file."
 
CleanUp:
 
        ChDirNet SaveDriveDir
 
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
        End With
    End If
End Sub

Open in new window

0
Comment
Question by:dking_wri
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 6

Accepted Solution

by:
Jaffa0 earned 2000 total points
ID: 24861101
Change this bit
            If intLastBaseRow > 1 Then
                intLastBaseRow = intLastBaseRow + 1
                intFirstRow = 2
            Else
                intFirstRow = 1
            End If

to this:

            If intLastBaseRow > 1 Then
                intLastBaseRow = intLastBaseRow + 1
                intFirstRow = 1
            Else
                intFirstRow = 1
            End If
0
 

Author Closing Comment

by:dking_wri
ID: 31603800
Worked perfectly.  Thanks for your help!
David
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article descibes how to create a connection between Excel and SAP and how to move data from Excel to SAP or the other way around.
In Part II of this series, I will discuss how to identify all open instances of Excel and enumerate the workbooks, spreadsheets, and named ranges within each of those instances.
This Micro Tutorial demonstrates how to create Excel charts: column, area, line, bar, and scatter charts. Formatting tips are provided as well.
This Micro Tutorial will demonstrate how to create pivot charts out of a data set. I also added a drop-down menu which allows to choose from different categories in the data set and the chart will automatically update.

722 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question