Solved

Copy Data from Text File

Posted on 2011-02-21
13
240 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:Cartillo
Comment Utility
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
Comment Utility
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
Comment Utility
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:Cartillo
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
Cartillo,
Did you chk the file I posted ?
Rgds/gowflow
0
 

Author Comment

by:Cartillo
Comment Utility
Hi gowflow,

Thanks for the solution.
0
 
LVL 29

Expert Comment

by:gowflow
Comment Utility
Your welocme my freind !
gowflow
0
 

Author Closing Comment

by:Cartillo
Comment Utility
Hi,

Thanks for the help.
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

A little background as to how I came to I design this code: Around 5 years ago I designed an add-in that formatted Excel files to a corporate standard, applying different cell colours and font type depending on whether the cells contained inputs,…
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 Micro Tutorial will demonstrate on a Mac how to change the sort order for chart legend values and decrpyt the intimidating chart menu.
This Micro Tutorial will demonstrate in Microsoft Excel how to add style and sexy appeal to horizontal bar charts.

772 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now