Solved

Copy Data from Text File

Posted on 2011-02-21
13
243 Views
Last Modified: 2012-05-11
Hi Experts,

I would like to request Experts help create a macro to copy data from .TXT file into Excel sheet automatically. I have attached the sample .TXT data that I would like to copy into the Excel sheet. The data need to be copied from Column A to Column F evenly so that the data from .TXT were not missed out. I have almost 500,000 data need to copy from .TXT file into this Excel sheet. I have manually copied few data at Excel sheet for Experts to get better view. Hope Experts will help me to create this feature.

 

Source.txt
Data-Check.xls
0
Comment
Question by:Cartillo
  • 5
  • 4
  • 3
  • +1
13 Comments
 
LVL 6

Assisted Solution

by:TinTombStone
TinTombStone earned 50 total points
ID: 34949468
This procedure will drop your text file data into A1:F56536 cell by cell left to right
You need to plug in your own text file details at   TextFileName = "Your file here  "

Sub GetTextData()

Dim fso As Object
Dim ts As Object
Dim cellCount As Long
Dim rngData As Range
Dim TextFileName As String
   
    Application.ScreenUpdating = False

    TextFileName = "C:\Course\Source.txt"  ' Change this to your textfile path and name

    Set fso = CreateObject("Scripting.FileSystemObject")

    If Not fso.FileExists(TextFileName) Then
        MsgBox "File name '" & TextFileName & "' is not valid.", vbExclamation, "Import Text File"
        Exit Sub
    End If

    Set ts = fso.OpenTextFile(TextFileName, ForReading)
   
    Set rngData = Range("A1:F65536")
   
    Do
        cellCount = cellCount + 1
        rngData.Cells(cellCount).Value = ts.ReadLine
   
    Loop Until ts.AtEndOfStream
   
    ts.Close
   
    Columns("A:F").ColumnWidth = 15
End Sub
0
 
LVL 59

Expert Comment

by:Chris Bottomley
ID: 34949474
The following inputs the data into a new sheet on every run.

edit C:\Users\<username>\Documents\source.txt to reflect your path and file name

Chris
Sub readText()
Dim objFSO As Object
Dim objStream As Object
Dim arr() As String
Dim elem As Variant
Dim ws As Worksheet
Dim rw As Long
Dim col As Integer

    Set objFSO = CreateObject("scripting.filesystemobject")
    Set objStream = objFSO.getfile("C:\Users\<username>\Documents\source.txt").openastextstream
    arr = Split(objStream.readall, vbCrLf)
    objStream.Close
    'Stop
    Set ws = ThisWorkbook.Worksheets.Add
    ws.Cells.NumberFormat = "@"
    rw = 0
    col = 1
    For Each elem In arr
        If LCase(Right(elem, 1)) = "a" Or IsNumeric(Right(elem, 1)) Then
            rw = rw + 1
            col = 1
        End If
        ws.Cells(rw, col) = elem
        col = col + 1
    Next
    ws.UsedRange.EntireColumn.AutoFit
    
End Sub

Open in new window

0
 
LVL 29

Expert Comment

by:gowflow
ID: 34949535
Hi Cartillo,

I have a question for you. I see your input text and the excel attached but I don't understand what is the criteria for putting data in Col A or B or C or D etc .... Do you have a specific pattern to store data in each column as you did not specified it. You simply mentioned in your original post

quote
" The data need to be copied from Column A to Column F evenly so that the data from .TXT were not missed out."
unquote

and if I see your sample you have for the first 10 lines:
000J01HS11A
000J01HS11B
000J01HS11C
000J01HS11D
000J01HS11E
000N01HS11A
000N01HS11B
000N01HS11C
00M101HS11A
00M101HS11B

and in the Excel you dont' have them in the same sequence
000J01HS11A      00M41A      00M101HS11B      00M601HS12D      000N01HS11A      00M601HS12A
000J01HS11B      00M41B      00M101HS11C      00M601HS12E      000N01HS11B      00M601HS12B
000J01HS11C      00M41C      00M301HS11A      00M601HS12F      000N01HS11C      00M601HS12C
000J01HS11D      00M6002EX11      00M301HS11B      00M601HS22A      00M101HS11A      
000J01HS11E      00M6003EX11      00M301HS11C      00M601HS22B            
Appreciate your clarification enabling give you the correct code !
Rgds/gowflow
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 

Author Comment

by:Cartillo
ID: 34949716
Hi Tim:

Have tested and it shows an error message at this line “Set ts = fso.OpenTextFile(TextFileName, ForReading)” as “invalid procedure call or argument”

Hi Chris:

Is that possible to copy the data between Column A to F at Data sheet instead of creating a new sheet? Hope this is possible.

Hi gowflow,

The data not necessarily need to be aligned according to specific criteria. As long as the whole data copied evenly from Column A to F will do. This is mainly because the actual Text file has more than 500,000 data.  
0
 
LVL 59

Expert Comment

by:Chris Bottomley
ID: 34949856
COpy to data sheet - easy peasy ... keep existing data or delete ... note if you want to merge the new and old that is something else entirely

Chris
0
 
LVL 29

Accepted Solution

by:
gowflow earned 250 total points
ID: 34949950
ok fine then pls try this attached example. You can simply rename the sheet to Data and delete your original one I kept it for refrence.

Rgds/gowflow
Data-Check.xls
0
 

Author Comment

by:Cartillo
ID: 34949993
Hi Chris,

No need to keep the old data. Is that possible not to specifically labeled the file name? Just sufficient with the folder name (D://datafile).
0
 
LVL 29

Expert Comment

by:gowflow
ID: 34950001
Oops forgot the instructins !!

1) Make sure Macro security is set to medium
2) Enable Macros when you open the file.
3) go to sheet Test and press on the command button "Import Text"
4) Select the file you wish to import, by default it goes to the location of the actual workbook
5) Check the results.
6) As previously mentioned, you can delete your original Data sheet and rename Test to Data.

Pls advise your comments
Rgds/gowflow
0
 
LVL 59

Assisted Solution

by:Chris Bottomley
Chris Bottomley earned 200 total points
ID: 34950036
See below.

Not sure what you mean by D://datafile but perhaps just replace the constatnt string ... added some sanity checking this time

Chris
Sub readText()
Dim objFSO As Object
Dim objStream As Object
Dim arr() As String
Dim elem As Variant
Dim ws As Worksheet
Dim rw As Long
Dim col As Integer
Dim strFileName As String

    strFileName = "C:\Users\<username>\Documents\source.txt"
    Set objFSO = CreateObject("scripting.filesystemobject")
    If Not objFSO.FileExists(strFileName) Then
        MsgBox "File " & strFileName & " NOT found"
    Else
        On Error Resume Next
        Set ws = ThisWorkbook.Worksheets("Data")
        If ws Is Nothing Then
            MsgBox "Worksheet DATA NOT Found"
        Else
            ws.Cells.Delete
            ws.Range("A1:F1").Cells = Array("Table1", "Table2", "Table3", "Table4", "Table5", "Table6")
            Set objStream = objFSO.getfile(strFileName).openastextstream
            arr = Split(objStream.readall, vbCrLf)
            objStream.Close
            'Stop
            ws.Cells.NumberFormat = "@"
            rw = 1
            col = 1
            For Each elem In arr
                If LCase(Right(elem, 1)) = "a" Or IsNumeric(Right(elem, 1)) Then
                    rw = rw + 1
                    col = 1
                End If
                ws.Cells(rw, col) = elem
                col = col + 1
            Next
            ws.UsedRange.EntireColumn.AutoFit
        End If
    End If
    
End Sub

Open in new window

0
 
LVL 29

Expert Comment

by:gowflow
ID: 34950062
Cartillo,
Did you chk the file I posted ?
Rgds/gowflow
0
 

Author Comment

by:Cartillo
ID: 34950068
Hi gowflow,

Thanks for the solution.
0
 
LVL 29

Expert Comment

by:gowflow
ID: 34950077
Your welocme my freind !
gowflow
0
 

Author Closing Comment

by:Cartillo
ID: 34950101
Hi,

Thanks for the help.
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Convert between Excel file formats (.XLS, .XLSX, .XLSM) with/without macro option David Miller (dlmille) Intro Over this past Fall, I've had the opportunity to see several similar requests and have developed a couple related solutions associate…
This tutorial explains how to create a series of drop-down lists that are dependent upon prior selections to guide (“force”) the user to make the correct selection and reduce data errors within Microsoft Excel. Excel 2010 was used for this tutorial;…
The viewer will learn how to use the =DISCRINV command to create a discrete random variable, use this command to model a set of probabilities and outcomes in a Monte Carlo simulation, and learn how to find the standard deviation of a set of probabil…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

775 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