Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Copy values from text file to excel

0

Hi,

I have a notepad with few rows. below is the notepad example.

I have Excel and the first row contains header like First name, Last-name, age, city, car and mobile. In my notepad few field value is empty and few fields are not there in few rows.

I want to copy the content to excel. If the field is not there or value is empty in notepad, it should not write anything into excel row.

I have attached the notepad and excel for reference.

Thanks in advance! 

Answer
Discuss

Discussion

Sivagokuk

Thanks for posing a fresh question for this. You say "... below is the notepad example"  but unless it's embedded in the Excel file, it doesn't show. You can't paste images or upload non-Excel files here. I'll check when I get to my PC
John_Ru (rep: 6142) Jul 12, '23 at 12:48 pm
Hi John_Ru.. apologize.. i copied the image in original post.. please find the content below:
First name=David last-name=dav age=32 city=tx car=maruti mobile=nokia
First name=Siva last-name=Kumar age=29 city=   car=bmw z510 mobile=samsung
First name=dal last-name=madona age=29 city=cb mobile=iPhone

In line 2 the city value is empty and in line 3 few fields are missing. So when the field value is empty or the field is not there it should not write any values to excel first row. Other value should write into Excel.
Sivagokuk (rep: 4) Jul 12, '23 at 12:58 pm
Thanks, understood.

If the text fields are always in the same order (even if blank), that would make it simpler
John_Ru (rep: 6142) Jul 12, '23 at 1:05 pm
Sorry John_Ru
It won't be in same order. 
Sivagokuk (rep: 4) Jul 12, '23 at 1:08 pm
Understood; still possible but be patient please 
John_Ru (rep: 6142) Jul 12, '23 at 1:20 pm
Sure. Thanks in advance!!
Sivagokuk (rep: 4) Jul 12, '23 at 1:22 pm
Add to Discussion

Answers

0
Selected Answer

Sivagokuk

In the discussions above, you confirmed that the text fields aren't always in the same sequence and won't be in same order.

This makes life tricky (you really should considered a structured format, e.g. comma-separation) but the attached file has your 6 headers and a new blue button labelled "Import header-matching values", linked to the macro below, It will import text files with contents like:

First name=David last-name=dav age=32 city=tx car=maruti mobile=nokia
First name=Siva last-name=Kumar age=29 city=   car=bmw z510

and - provided the text file has entries identical to the header (so "Last-name" not "Last name") - will handle fields in any order or missing in a line but is limited to importing a single word per field. You'd need to have "BMW_z510" to get both words.

It will import text into free rows after any existing entries in A:F

I've added comments so you can perhaps follow what is happening:

Sub ImportUnstructuredText()

    Dim ThisLine As Variant
    Dim fileFilterPattern As String
    Dim MyOperator As String, n As Long, p As Long
    Dim Fields() As Variant, FieldStart As Long, NextOp As Long
    Dim NxtFree As Long

    MyOperator = "="
    ' work out next unused row in any column
    NxtFree = ActiveSheet.UsedRange.Rows.Count + 1
    ' load headers to array
    Fields = ActiveSheet.Range("A1:F1").Value

    ' Open a file but just look at text files
    fileFilterPattern = "Text Files *.txt,*.txt"

    ThisLine = Application.GetOpenFilename(fileFilterPattern)

    If ThisLine = False Then
        MsgBox "No file selected."
        Exit Sub
    End If

    Application.ScreenUpdating = False

    Open ThisLine For Input As #1
    ' Look at each line of the file
    Do Until EOF(1)
        Line Input #1, ThisLine
        ' If the line contains something
        If Len(ThisLine) > 0 Then
            ' add a trailing space
            ThisLine = ThisLine & " "
            ' loop through headers and search for in text line
            For p = 1 To 6
                'see if field name is in line
                If InStr(LCase(ThisLine), LCase(Fields(1, p)) & MyOperator) > 0 Then
                    'determine where any text starts after column header and operator (compare lowercase)
                    FieldStart = InStr(LCase(ThisLine), LCase(Fields(1, p)) & MyOperator) + Len(Fields(1, p) & MyOperator)
                    ' calculate where next space is after that
                    NextOp = InStr(FieldStart, ThisLine, " ")
                    ' put text between under that header
                    Cells(NxtFree + n, p).Value = Mid(ThisLine, FieldStart, NextOp - FieldStart + 1)
                End If
            Next p
        End If
        ' Point to next row
        n = n + 1
    Loop

    ' Done so close the file for input
    Close #1

    Application.ScreenUpdating = True
    'tell user
    MsgBox "Imported " & n & " records from text file"

End Sub

Hope this helps- if so, please remember to mark it as Selected.

Discuss

Discussion

Thank you so much. Its working. Is there any option to include the value even aftre space (BMW Z510). 
Sivagokuk (rep: 4) Jul 12, '23 at 10:10 pm
Thanks for selecting my Answer, Sivagokuk. 

Getting fields containing spaces would involved extra logic/ looping (probably) snd I don't have spare time in the next couple of days.

How many unstrictured recorrds do you have? 
John_Ru (rep: 6142) Jul 13, '23 at 1:40 am
Thanks John_Ru..
Sorry for the delayed response.
I have around 26 records
Sivagokuk (rep: 4) Jul 21, '23 at 7:49 am
Sivagokuk

Thanks but it's not worth creating a whole new VBA approach for just 26 records- you can easily check those manually.
John_Ru (rep: 6142) Jul 21, '23 at 8:42 am
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login