[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

Copy Data from Text File

Posted on 2011-02-21
13
Medium Priority
?
251 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
[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
  • 5
  • 4
  • 3
  • +1
13 Comments
 
LVL 6

Assisted Solution

by:TinTombStone
TinTombStone earned 200 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 31

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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

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 31

Accepted Solution

by:
gowflow earned 1000 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 31

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 800 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 31

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 31

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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

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

Excel can be a tricky bit of software to get your head around. Whilst you’ll be able to eventually get to grips with the basic understanding of how to get by, there are a few Excel tips that not everybody will even know about let alone know how to d…
Access developers frequently have requirements to interact with Excel (import from or output to) in their applications.  You might be able to accomplish this with the TransferSpreadsheet and OutputTo methods, but in this series of articles I will di…
The viewer will learn how to use a discrete random variable to simulate the return on an investment over a period of years, create a Monte Carlo simulation using the discrete random variable, and create a graph to represent the possible returns over…
This Micro Tutorial will demonstrate how to use longer labels with horizontal bar charts instead of the vertical column chart.

656 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