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

Import text files in excel within selected cells using VBA

0

I've been trying to open text files into excel using vba. I want to access any text file and import it fast by clicking one button. I generated a vba code (with the help of a YT video: Automated Text Import in Excel with File Selection - The Easy Way - VBA - YouTube), but the issue is that when I run the code (press the import button), I only get a small portion of the text. Excel only reads up to a point where it finds a space between rows. It also makes each word go to a single cell for the "UW PID" file. Additionally, what can I add to my code so that when I click the "Import" button, I can simply select the cell where I want to import the file to in the same worksheet. in other words, use the same button, but import three different files in any selected cells. This link has the type of files I`m trying to import: https://www.dropbox.com/scl/fo/ipyyorn96vtx5zy7anr1a/h?dl=0&rlkey=9liwhym9gunbx9nanmzrnak97

Here is the code to help me with the import:

Sub ImportText()
    Dim UWDT As Variant
    Dim fileFilterPattern As String
    Dim RawDust As Worksheet
    Dim wbTextImport As Workbook
    Application.ScreenUpdating = False
    fileFilterPattern = "Text Files (*.txt; *.csv),*.txt;*.csv"
    UWDT = Application.GetOpenFilename(fileFilterPattern)
    If UWDT = False Then
        MsgBox "No file selected."
    Else
        Workbooks.OpenText _
            Filename:=UWDT, _
            Origin:=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
        Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), _
        Array(2, 1), Array(3, 1)), TrailingMinusNumbers:=True   

        Set wbTextImport = ActiveWorkbook
        Set RawDust = ThisWorkbook.Worksheets("Dust Raw Data")
        wbTextImport.Worksheets(1).Range("A1").CurrentRegion.Copy RawDust.Range("A2")
        wbTextImport.Close False
        
    End If
    Application.ScreenUpdating = True
 
[/CODE]End Sub
Answer
Discuss

Discussion

My revised answer is probably what you need (given your clarification to my original answer) 
John_Ru (rep: 6142) Apr 24, '23 at 9:51 am
Hi,
Yes! this worked perfectly. The only change I had to make was comvert the text to numbers for the cells that had numbers. Appreciate your help!
josuec52 (rep: 4) Apr 24, '23 at 7:06 pm
Great. Glad you fixed the cell formatting and have a working solution. 
John_Ru (rep: 6142) Apr 25, '23 at 1:36 am
Add to Discussion

Answers

0
Selected Answer

Hi Josuec52 and welcome to the Forum

If I understand you correctly, you want to import text files but not have to import values into separate cells (your sample PID file has data separated by tabs so the Tab=True part of your macro forces data into separate cells).

Furthermore, to avoid the macro stopping at the first blank line, I suggest you use VBA's Open statement instead (Microsoft guideline is here: Open statement).

In the first attached file, you'll see a new lilac button "Import text to a cell" on the worksheet "Dust Raw Data". That has the following macro assigned and allows you to pick a sheet and cell to import any text file (with each line of text in the same column). It will identify the file imported and include blank lines.

Sub ImportText2()

    Dim UWPID As Variant
    Dim fileFilterPattern As String
    Dim Dest As Range, n As Long

    ' Just look at text files
    fileFilterPattern = "Text Files *.txt,*.txt"

    UWPID = Application.GetOpenFilename(fileFilterPattern)

    If UWPID = False Then
        MsgBox "No file selected."
    Else
        ' Get user to pick a single cell (and loop until they do)
        Do
            Set Dest = Application.InputBox("Pick a SINGLE cell to start the text input" & Chr(13) & "(Note: needs clear cells below)", Type:=8)
        Loop Until Dest.Count = 1

        ' Show the sheet containing that cell
        Dest.Parent.Activate
        ' Write source in chosen file
        Dest.Value = "Imported from file: " & UWPID
        Dest.Font.Bold = True

        Application.ScreenUpdating = False

        Open UWPID For Input As #1
        ' Look at each line of the file
        Do Until EOF(1)
            Line Input #1, UWPID
            n = n + 1
            Dest.Offset(n, 0).Value = UWPID
        Loop

        ' Done so close the file for input
        Close #1
        'expand column to show data
        Columns(Dest.Column).AutoFit
    End If
    Application.ScreenUpdating = True

End Sub

It should work for both of your file types.

Revision 22 April 2023:

Further to your discussion point preferring to paste from the active cell and to separate cells by tab or comma, the second attached sample import text file to active cell v0_b.xlsm has the lilac button caption "Import text to active cell" on the worksheet "Dust Raw Data" and has the following revised macro assigned to it (with comments to guide you). Note that the variable UWPID above is replaced by ThisLine (since it works with your UWPID and UW DP files):

Sub ImportText3()

    Dim ThisLine As Variant
    Dim fileFilterPattern As String
    Dim n As Long

    ' 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
            ' Replace any commas with tabs (ASCII character 9)
            ThisLine = Replace(ThisLine, ",", Chr(9))
            ' Divide string into an array by tab
            ThisLine = Split(ThisLine, Chr(9))
            ' Copy array to a resized range
            ActiveCell.Offset(n, 0).Resize(1, UBound(ThisLine) + 1).Value = ThisLine
        End If
        ' Point to next cell below
        n = n + 1
    Loop

    ' Done so close the file for input
    Close #1

    Application.ScreenUpdating = True

End Sub

The key changes are in bold above and mean files with tab or comma separations have the string converted to an array so they are copied to 1 or more cells (if there's a tab or comma in the line)

Hope this works for you.

Discuss

Discussion

Hi John_Ru
Thank you for the help. Your code does load all the data, but does not separate the text based on commas. Also, I like the "Choose the cell" box, but I was thinking if it would be a bit faster if the cell is already selected prior to running the macro and I simply import it to that active cell? 
Also, I`d like to have my txt file as is but start in the second row instead of having the "Imported from file" text. If I do get rid of it, I have the second row blank and it starts from the third.

My apologies for basic questions as I just started learning VBA!!
josuec52 (rep: 4) Apr 22, '23 at 11:00 am
Okay, please see revised file and second file. I had the "pick a cell" feature on the assumption others would use the file. If it's just you, your knowledge and the new button caption should be enough  

Thanks for marking my Answer as Selected but on future questions, you can delay that until the question has been answered satisfactorily. Please don't however keep adding new aspects to your question- that gives more work to people (like me) trying to help you and tends to annoy us!
John_Ru (rep: 6142) Apr 22, '23 at 5:25 pm
@john_Ru @josuec52
hi, I've trying to do the same thing! And you were able to help my problem. However, in my case; excel cannot register the time and dates and it only reads as text. Also, how were you able to fix the text to number conversion? What lines can I add to this problem? THANKS!
Isacri05 (rep: 2) May 2, '23 at 8:13 pm
Hi Isacri05 and welcome to the Forum.

Please ask a new question on this and use the Add Files... button below the question text to attach a representative Excel file (and embed a .csv file in that - since only Excel files can be uploaded). We should then be able to provide you with an answer
John_Ru (rep: 6142) May 3, '23 at 1:09 am
Add to Discussion


Answer the Question

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