mporting multiple text files into Excel with corresponding filenames

Dear members,

I need to import 100+ text files into Excel.

In addition I want Excel to show corresponding filename (where the
data comes from) in each row.

How do I accomplish this?
TIA
0
avi
2/3/2010 11:07:58 AM
excel.programming 6508 articles. 2 followers. Follow

11 Replies
1093 Views

Similar Articles

[PageSpeed] 24

Hi

Take a look at Ron de Bruin's site. He has lots of code examples to 
consolidate files.
http://www.rondebruin.nl/tips.htm
-- 
Regards
Roger Govier

"avi" <avi38521@gmail.com> wrote in message 
news:9194d7dc-21bb-4fd9-8ecb-aa301a54f7d1@b2g2000yqi.googlegroups.com...
> Dear members,
>
> I need to import 100+ text files into Excel.
>
> In addition I want Excel to show corresponding filename (where the
> data comes from) in each row.
>
> How do I accomplish this?
> TIA
>
> __________ Information from ESET Smart Security, version of virus 
> signature database 4830 (20100203) __________
>
> The message was checked by ESET Smart Security.
>
> http://www.eset.com
>
>
> 

__________ Information from ESET Smart Security, version of virus signature database 4830 (20100203) __________

The message was checked by ESET Smart Security.

http://www.eset.com



0
Roger
2/3/2010 11:31:34 AM
Specify the folder and try the below..

Sub Macro()

Dim strFolder As String, strFile As String
Dim strData As String, intFile As Integer, lngRow As Long

strFolder = "D:\PhoneNo"
If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\"

strFile = Dir(strFolder & "*.txt", vbNormal)
Do While strFile <> ""
    intFile = FreeFile
    Open strFolder & "\" & strFile For Input As #intFile
    Do While Not EOF(intFile)
    Line Input #intFile, strData
    lngRow = lngRow + 1
    Range("A" & lngRow) = strFile
    Range("B" & lngRow) = strData
    Loop
    Close #intFile
strFile = Dir
Loop


End Sub

-- 
Jacob


"avi" wrote:

> Dear members,
> 
> I need to import 100+ text files into Excel.
> 
> In addition I want Excel to show corresponding filename (where the
> data comes from) in each row.
> 
> How do I accomplish this?
> TIA
> .
> 
0
Utf
2/3/2010 11:57:02 AM
Thanks Jacob! Works perfect!
Just one note (that I forgot to mention): data in my text files is
comma delimited.
Your code imports correctly filenames & data BUT all the data is
imported into one cell.
OK, I can use "text to columns" but would like to have it
delimited.... :-)

0
avi
2/3/2010 12:25:25 PM
That was not mentioned in the original post..I have modified to suit your 
requirement.

Sub Macro()

Dim strFolder As String, strFile As String, lngRow As Long
Dim strData As String, arrData As Variant, intFile As Integer

strFolder = "D:\PhoneNo"
If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\"

strFile = Dir(strFolder & "*.txt", vbNormal)
Do While strFile <> ""
    intFile = FreeFile
    Open strFolder & "\" & strFile For Input As #intFile
    Do While Not EOF(intFile)
    Line Input #intFile, strData
    arrData = Split(strData, ",")
    lngRow = lngRow + 1
    Range("A" & lngRow) = strFile
    Range("B" & lngRow).Resize(, UBound(arrData) + 1) = arrData
    Loop
    Close #intFile
strFile = Dir
Loop


End Sub

-- 
Jacob


"avi" wrote:

> Thanks Jacob! Works perfect!
> Just one note (that I forgot to mention): data in my text files is
> comma delimited.
> Your code imports correctly filenames & data BUT all the data is
> imported into one cell.
> OK, I can use "text to columns" but would like to have it
> delimited.... :-)
> 
> .
> 
0
Utf
2/3/2010 1:08:02 PM
Jacob Skaria wrote:
> =A0 =A0 arrData =3D Split(strData, ",")

That will fail if a quoted value contains a comma.

Phil Hibbs.
0
Phil
2/3/2010 3:09:07 PM
Why ?

"Phil Hibbs" <snarks@gmail.com> wrote in message 
news:d593ce58-67c9-40d8-bf00-e1eb3460eeec@21g2000yqj.googlegroups.com...
Jacob Skaria wrote:
> arrData = Split(strData, ",")

That will fail if a quoted value contains a comma.

Phil Hibbs. 


0
Peter
2/3/2010 3:32:02 PM
>> That will fail if a quoted value contains a comma.
> Why ?

I assume that the CSV that the OP has conforms to the Microsoft
format, and that code will convert this:

Phil Hibbs,Programmer,"$100,000"

into this:

[Phil Hibbs] [Programmer] ["$100] [000"]

where [] indicates a cell.

Phil Hibbs.
0
Phil
2/3/2010 5:15:10 PM
Fair point. If the OP's files include commas within values (not just as a 
thousands separator) more work or a different approach is required.

Regards,
Peter T


"Phil Hibbs" <snarks@gmail.com> wrote in message 
news:46ddb066-fa79-4f5d-8157-7d47a0048663@m16g2000yqc.googlegroups.com...
>>> That will fail if a quoted value contains a comma.
>> Why ?
>
> I assume that the CSV that the OP has conforms to the Microsoft
> format, and that code will convert this:
>
> Phil Hibbs,Programmer,"$100,000"
>
> into this:
>
> [Phil Hibbs] [Programmer] ["$100] [000"]
>
> where [] indicates a cell.
>
> Phil Hibbs. 


0
Peter
2/3/2010 5:34:34 PM
I would probably go with a solution that involves using the Excel
import code to read each file into a blank tab, and then copy that
data from the tab into the combined tab. Here's an example of a macro
that imports data into a new tab:

    ActiveWorkbook.Worksheets.Add
    ActiveSheet.Name = "Tempsheet"

    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" _
           + FileName, Destination:=Range("A1"))
        .Name = "CSVfile"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2)
        .Refresh BackgroundQuery:=False
    End With

The big 2, 2, 2, 2, 2 line defines all columns (up to 100) as Text.
Next you would need to copy-paste the contents of this tab into the
real tab and fill in the file name, then delete the tab and import the
next file. You could turn off screen updates while this is happening.
Or hide the temporary tab.

Phil Hibbs.
0
Phil
2/3/2010 5:50:50 PM
Phil Hibbs wrote:
> I would probably go with a solution that involves using the Excel
> import code to read each file into a blank tab, and then copy that
> data from the tab into the combined tab. Here's an example of a macro
> that imports data into a new tab:
> 

> 
> Phil Hibbs.

Other way is to use TextToColumns method. Using Jacob's code, it looks 
like this. but, No test.

Sub Macro()

Dim strFolder As String, strFile As String, lngRow As Long
Dim strData As String, arrData As Variant, intFile As Integer

strFolder = "D:\PhoneNo"
If Right(strFolder, 1) <> "\" Then strFolder = strFolder & "\"

strFile = Dir(strFolder & "*.txt", vbNormal)
Do While strFile <> ""
     intFile = FreeFile
     Open strFolder & "\" & strFile For Input As #intFile
     Do While Not EOF(intFile)
     Line Input #intFile, strData
     lngRow = lngRow + 1
     Range("A" & lngRow) = strFile
     Range("B" & lngRow) = strData
     Loop
     Close #intFile
     strFile = Dir
Loop
Columns("B").TextToColumns Destination:=Columns("B"), _
     DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
     ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, _
     Comma:=True, Space:=False, Other:=False
End Sub

Keiji
0
keiji
2/4/2010 4:30:03 AM
Hi Phil

Thanks for your thoughts. We are not sure since the OP has not come back. A 
better way would be to use the .OpenText method as below...

Workbooks.OpenText Filename:="D:\PhoneNo\2.txt", StartRow:=1 , _
DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, Comma:=True


-- 
Jacob


"Phil Hibbs" wrote:

> I would probably go with a solution that involves using the Excel
> import code to read each file into a blank tab, and then copy that
> data from the tab into the combined tab. Here's an example of a macro
> that imports data into a new tab:
> 
>     ActiveWorkbook.Worksheets.Add
>     ActiveSheet.Name = "Tempsheet"
> 
>     With ActiveSheet.QueryTables.Add(Connection:="TEXT;" _
>            + FileName, Destination:=Range("A1"))
>         .Name = "CSVfile"
>         .FieldNames = True
>         .RowNumbers = False
>         .FillAdjacentFormulas = False
>         .PreserveFormatting = True
>         .RefreshOnFileOpen = False
>         .RefreshStyle = xlInsertDeleteCells
>         .SavePassword = False
>         .SaveData = True
>         .AdjustColumnWidth = True
>         .RefreshPeriod = 0
>         .TextFilePromptOnRefresh = False
>         .TextFileStartRow = 1
>         .TextFileParseType = xlDelimited
>         .TextFileTextQualifier = xlTextQualifierDoubleQuote
>         .TextFileConsecutiveDelimiter = False
>         .TextFileTabDelimiter = False
>         .TextFileSemicolonDelimiter = False
>         .TextFileCommaDelimiter = True
>         .TextFileSpaceDelimiter = False
>         .TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, _
> 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
> 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
> 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, _
> 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
> 2)
>         .Refresh BackgroundQuery:=False
>     End With
> 
> The big 2, 2, 2, 2, 2 line defines all columns (up to 100) as Text.
> Next you would need to copy-paste the contents of this tab into the
> real tab and fill in the file name, then delete the tab and import the
> next file. You could turn off screen updates while this is happening.
> Or hide the temporary tab.
> 
> Phil Hibbs.
> .
> 
0
Utf
2/4/2010 4:36:01 AM
Reply:

Similar Artilces:

How to repair a .dll file in IE8
Several days ago I noticed in my Dependency Walker that the IESHIMS.dll files has a yellow circle with a question mark on it. What does this mean and How do I repair it? OS: Windows Vista Home Premium Browser Internet Explorer 8 -- TW Hi, See the History tab on that dialog. A web search for ieshims.dll files will also help you find a solution for that file. Regards. "TW" <TW@discussions.microsoft.com> wrote in message news:63E61463-D766-4ABC-B081-BFA8C04FB159@microsoft.com... > Several days ago I noticed in my Dependency Walker that the IESHIMS....

Using Relative path for XML data file?
Is there a way to specify a relative path to an XML data file imported into Excel 2003? I am writing a web app that generates report data as XML for the user to download to their local machine. This data is to be consumed by an Excel reporting spreadsheet, which contains display-formatted tables and charts that are mapped to various data fields in an XML Map, which is in turn linked to the xml data file they will download. The idea is the user only needs to download the data for updates, not the whole spreadsheet. However, since I cannot predict the path where the user will store their...

unsolicited entry in the folder "Temporary Internet Files"
Hello, I am working on a programme which browses web sites and runs under XP. The http download is as follows: pServer = Isession -> GetHttpConnection(strServerName, nPort); pFile = pServer->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject, NULL, 1, NULL, NULL, dwHttpRequestFlags); pFile->SendRequest(); pFile->QueryInfoStatusCode(dwStatusCode); if(dwStatusCode == 200) { pFile -> QueryInfo(HTTP_QUERY_LAST_MODIFIED, &sysT); status.lastMod = sysT; if(DBlastMod == status.lastMod) //URL content has not changed since the last visit ...

Excel button problem
Hi All I have a macro that copies a worksheet in the active workbook and puts it into a new workbook - then formats it and deletes any buttons on the worksheet. On the first click on the button the macro works ok. On the second click, it fails because the all assigned macros on all buttons in the active workbook changed from "mba" to "book1!mba". Book 1 doesn't exists (wasn't opened, wasn't saved, doesn't have the macros). I've never experienced this problem before?? Can anyone help to solve this problem? FYI The macro to do this is c...

Excel 97 #9
Please can anyone help??? I have two columns in Excel 97. The first contains a list of statu values eg. pending, or granted or withdrawn. The second contains date eg.01/12/1997, 05/06/2003. I woudl like to know how to get all th granted apps before 31/12/2003. Can anyone help please -- Message posted from http://www.ExcelForum.com theres many ways, but an easiest way would be to do a sort. Highlight the 2 columns, click on data, then sort, then sort by status, then by date. this should group them all together. hope this helps...toe >-----Original Message----- >Please can anyo...

how to convert lookup values to the "display text"
I'm using an sql code (below) which uses a few lookup fields. Unfortunately in the datasheet view, I get the "bound values" instead of the "display values". How can I change the properties for the these lookup fields so I can see the "display values" from the datasheet view? SELECT [Funding],[Date],[Description],[Company],[Expense_Type],[Amount],[Status] FROM [Form_9_Status] UNION ALL SELECT [Funding],[Date],[Description],[Company],[Expense_Type],[Amount],[Status] FROM [TDY_Status] UNION ALL SELECT [Funding],[Date],[Description],[C...

Linking files 2 ways
I have a work book that is linked to another and vise versa. As thus: Workbook A is where the input of data is made; Workbook B has a link to the input from workbook A; Workbook A retrieves the altered data back as a link. Although this all works fine with both books open, I note that if I open workbook A by itself, that the data it retrieves from Workbook B is not updated . If However, both books are open, there's no problem. I thought linked books were updated automatically if the Update remote references has been selected?? But it appears that the second book is not updated until it ...

OL2007 not move big files from outbox to sent
Hi, We have 2 computers with separate email accounts on Roadrunner. One machine has XP with Outlook 2002-sp3 and works without any problems. The other has Outlook 2007 on Vista and has problems sending files over a meg or so in size. It seems to actually send the file but the file remains in the outbox folder and does not move it to the sent folder. I say it "seems" to send the file because some people complain of getting muliple copies and others don't seem to get them at all. If I hit send again (not set up for auto send) it seems to send the file again (why some ...

File size #11
I have read the other discussions on file sizes but they do not seem to address my problem. I have an Excel file that is 12mb large with low-res jpegs in it. This file also has merged cells to make it look pretty. Does Excel look at these merged cells as graphics? Is this why they are too big? I have run a macro to make sure that it goes to the last cell. How can I get the file smaller? How big are the graphics? If you remove them from the file, what is the size of the file and what is the size of the graphic files? To be sure you do not have extra formatting, if you open the file...

find action on log file
Hello there I want to use outside tool to find who made some update on table in my server I know that there are many tools for this. But can they do it on simple recovery model? Roy Goldhammer (royg@yahoo.com) writes: > I want to use outside tool to find who made some update on table in my > server > > I know that there are many tools for this. But can they do it on simple > recovery model? No. If you are using the simple recovery model, the contents of the log is wasted away everyonce in a while. Well, if the disk area has not been overwritten...

Looking for Excel Help
I'm a very novice Excel user and am looking for a little help with creating a formula for a spreadsheet I'm creating for my personal use. I would appreciate some assistance if possible. Thanks in advance. Dan --- Message posted from http://www.ExcelForum.com/ Hi Dan! Post a sample of what you want to do. Your question is just a tad open ended <g> -- Regards Norman Harker MVP (Excel) Sydney, Australia njharker@optusnet.com.au Excel and Word Function Lists (Classifications, Syntax and Arguments) available free to good homes. "DanB4105" <DanB4105.ywtpa@excelfor...

New to excel
Hi All, I'm new to Excel ( and to this forum :) ) and so I hope somebody may b able to help me. I've got 2 questions.... QUESTION 1 I've got a spreadsheet which takes data from one worksheet and uses i to calculate data in a second worksheet using the following code formula: =IF('4th November 2005'!B19="","nothing here dude",IF(B19<'4th Novembe 2005'!B19,"UP",IF(B19='4th November 2005'!B19,"Same",IF(B19>'4t November 2005'!B19,"DOWN")))) The problem is, when I create a new worksheet I have...

Maximum file sizes
Is there a recommended maximum file size for Excel 2000. PC spec 2Ghz P4 with 256 Mb Any advice appreciated Deus -------------- Does Not Exist Hi have a look at http://www.decisionmodels.com/memlimits.htm -- Regards Frank Kabel Frankfurt, Germany "Deus DNE" <deus.dne@ntlworld.com> schrieb im Newsbeitrag news:1561701c41d4f$358950f0$a001280a@phx.gbl... > Is there a recommended maximum file size for Excel 2000. > > PC spec 2Ghz P4 with 256 Mb > > Any advice appreciated > > Deus > -------------- > Does Not Exist ...

How do I overlay text to a row without loosing the text in the ba.
I would like to know how to give an entire row (or column) a text overlay such as "VOID" and still be able to view the text in the underlaying row (or column). Thanks in advance. Use WordArt from the Drawing toolbar. Change the Fill to None. -- Jim Rech Excel MVP "Bruce Charles" <Bruce Charles@discussions.microsoft.com> wrote in message news:C430F6BC-1EBD-461F-A3FA-EC8592C5704C@microsoft.com... |I would like to know how to give an entire row (or column) a text overlay | such as "VOID" and still be able to view the text in the underlaying row (or | c...

Excel corrupts when asking to update vlookups
We are experiencing weird behavior with some Office 2K3 Excel spreadsheets that contain lots of calculations, but no macros. On some pc’s Excel acts normally, on others you get the error. I have a couple of screen shots available. Any help is appreciated. If desired, send your file to my address below. I will only look if: 1. You send a copy of this message on an inserted sheet 2. You give me the newsgroup and the subject line 3. You send a clear explanation of what you want 4. You send before/after examples and expected results. -- Don Gu...

Uninstall of mappoint has caused errors with excel
Hi, I am running Office 2003 on the terminal server (windows 2003) and had a copy of mappoint as well. This is a mapping program. We ininstalled mappoint which has caused an error message with Excel and other office products. The error says "Cd:\documents and settings\administrator.ocrdc1\application data\microsoft\addins c:\Program files\common files\microsoft shared\geography\mpoai9.dll is not a valid add-in." I then click OK and excel opens up and everything is fine. The problem is that we are using other programs as well such as Quickbooks that export to excel and t...

CSV Files and VLOOKUP error
Does anyone know why VLOOKUP and Compare formulas don't work o information originating from a CSV file? I've tried copying an pasting values only (to leave behind any formatting), but it doesn' help. Through countless tests, I've narrowed it down to the CSV file bein the only possible cause -- Message posted from http://www.ExcelForum.com Hi ajpowers, Just a guess but the imported data may have leading or trailing spaces or are numbers stored as text. You could use the formula =A1=D1 to see if you get a true or false, where A1 is the lookup value and D1 ia the CVS valu...

How to automate increasing the form cache registry/file etc...
I want to roll out a batch file to make a number of tweaks to CRM The body of it would go REGEDIT /S Kerberosefix.reg REGEDIT /S ForceFormreload.reg REGEDIT /S OutlookFix.reg It would also rename OSA.exe to OSA.bad Remove OSA.exe From the startup menu I need help finding a way to use my batch file to increase the Outlook Form cache from the default 4MB to 50 MB.. This makes CRm more stable and faster for communications. I dont want to manually do this, as it time consuming, are my end users would not be reliable in doing it themselves. I also want to make another batch file or button that...

How do I Remove a Split from my Comments in Excel 2003? #2
I have set my current workbook to split/freeze the first column and first 2 rows. Now, when I add a comment to the second row (in any column) my comments are cut off if I should scroll down. I don't ever remember the behavior before. And I don't know what I've done to enable it but it's really annoying. How do turn this off ? ...

print multiple pages on one sheet of paper
I am using mailmerge in Publisher to create placecards for a party we are hosting. The final size of the placecards is 1.5" by 1.5" and we have to print 100 final cards. Publisher gives me the option of printing multiple copies of the same page on one sheet of letter sized paper or one page on one sheet of letter sized paper. What I would like to do, however, is print multiple different pages on one sheet of paper. If I cannot find a solution for this, I will need to print 100 separate pages with a 1.5" square box of copy in the center of each sheet. In page setup, sel...

learning Excel #3
Hi, I was considering learning Excel as an additional tool for my data analysis work. Is it better to use data sets that I have previously used with SPSS and apply the same analysis tools as in SPSS? For applying the appropriate tools, I was considering using excel's online help. The second option I have is to use some excel book for data analysis and apply the techniques to data sets provided with the book. Any suggestions????? regards Metal ...

unable to paste Excel 2003 chart into Outlook 2003
(This was posted on "excel.charting" group.) I have a user who's unable to paste an Excel 2003 chart into Outlook 2003 email message. In Outlook options, the checkbox is selected for "Use Microsoft Office Word 2003 to edit e-mail messages". When I tested this on my own computer running the same version of Office, if the box is check, I have no problem pasting; if this box is cleared, I cannot paste. But on his computer, it doesn't work regardless. Thanks and regards, TL ...

Excel VBA
When you select the autofilter, the drop down list is created from the unique data in that column. Is there any way to customize this list, so the changes are permanent? For instance, I might have in one(1) column the following 4 row entries: red, blue, green (all are single cell entries) red, blue red blue, green I want my autofilter drop down list to read: red instead of red, blue, green blue red, blue green red blue, green (like normal) If I chose red from the drop down list...

Problem with named range for a large spreadsheet in Excel 2007
Hello, I am trying to generate a large Excel spreadsheet apprx. 10000 rows and 40 columns. I am generating defined name section in the Workbook.xml part of the XLSM package. Here is a sample entry from that section <definedName name="_._44802_._0_._0_._0_._top_line" localSheetId="0" hidden="1">Sheet1!$B$2</definedName> Although the generation goes fine, I can not open the spreadsheet as the Excel throws an error message saying the package is corrupt. But this is not the case if the spreadsheet is small say, 200 rows by 10 columns. ...

how do I add error bars to a 3D chart in excel?
The help states you can only add error bars to data series in 2D area. Is there a way to add them to a 3D chart? Hi, I would not have thought so. Obviously as it is not a built-in option the only way would be a work around perhaps using dummy series. Unfortunately you can create 3d combination charts. Stick with the 2d view. Cheers Andy elahe wrote: > The help states you can only add error bars to data series in 2D area. Is > there a way to add them to a 3D chart? -- Andy Pope, Microsoft MVP - Excel http://www.andypope.info I checked, and error bars are not offered for 3D ch...