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

Multiple .dat file import into Excel - VBA

0

Hi all. I have a bit of a problem. I have a VBA code that imports multiple selected .dat files from a folder into Excel, then executes text to columns and some other minor things. My problem is that if I add an IF sentence to End Sub in case I cancel the file selection 

If datfilesToOpen = False Then
          MsgBox "No file selected"

I get a Run-time error '13': Type mismatch if I select any files to import. If I cancel selection I only get the message "No file selected" as per MsgBox.

Does anyone know what can be done to counter this error? I need this IF sentence in case I ever cancel file selection so the rest of the code independent of selected files (Excel sheet editing) doesn't execute.

Furthermore I need to have a file name imported for each file that is imported into Excel, as there can be many different files and I need to know which data goes with which file. Does anyone know how to implement that also into the existent code below?

I thank all in advance!

Sub ImportText_bckp()

    Dim fso As Object
    Dim qt As QueryTable
    Dim cn As Variant
    Dim datfilesToOpen As Variant, datfile As Variant

    Application.ScreenUpdating = False
    Set fso = CreateObject("Scripting.FileSystemObject")

    ' Opens folder to select files
    datfilesToOpen = Application.GetOpenFilename _
                (FileFilter:="Text Files (*.dat), *.dat", _
                MultiSelect:=True)

    If datfilesToOpen = False Then
        MsgBox "No file selected"
    Else

        ' Clears current entries
        If IsEmpty(Range("C4").Value) = False Then
            Range("C4").Select
            Range(Selection, Selection.End(xlToRight)).Select
            Range(Selection, Selection.End(xlDown)).Select
            Selection.ClearContents
        End If

        ' Inserts column for raw data entry
        Columns("A:A").Select
        Range("A3").Activate
        Selection.insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

            With ActiveSheet

                For Each datfile In datfilesToOpen

                    importrow = 1 + .Cells(.Rows.Count, 1).End(xlUp).Row

                     With ActiveSheet.QueryTables.Add(Connection:= _
                    "TEXT;" & datfile, Destination:=.Cells(importrow, 1))
                    .TextFileStartRow = 16
                    .TextFileParseType = xlFixedWidth
                    .TextFileTabDelimiter = True
                    .Refresh BackgroundQuery:=False
                    .AdjustColumnWidth = False
                     End With

                Next datfile

                For Each qt In ActiveSheet.QueryTables
                qt.delete
                Next qt

                For Each cn In ThisWorkbook.Connections
                cn.delete
                Next cn

            End With

            Range("A2").Select
            Range(Selection, Selection.End(xlDown)).Select
            Selection.TextToColumns Destination:=Range("D4"), DataType:=xlFixedWidth, _
            FieldInfo:=Array(Array(0, 1), Array(4, 1), Array(35, 1), Array(48, 1), Array(59, 1), _
            Array(65, 1), Array(76, 1)), TrailingMinusNumbers:=True

            Columns("A:A").Select
            Selection.delete Shift:=xlToLeft

            Cells.Select
            Cells.EntireColumn.AutoFit
            Range("A4").Select

            MsgBox "Successfully imported .dat files", vbInformation, "SUCCESSFUL IMPORT"
    End If
End Sub
Answer
Discuss

Discussion

Hi and Happy New Year.

Seems you just modified your question but I can't see how it has changed or recall in full your original question (from 4 weeks ago).

Please create a new question with your new query and file. 
John_Ru (rep: 6142) Jan 3, '22 at 3:38 am
Hi John, happy new year to you too!

I'm sorry for the confusion, I didn't modify anything, just removed my G-drive link. All is clear!
mkramar (rep: 2) Jan 3, '22 at 5:41 am
Okat, thanks
John_Ru (rep: 6142) Jan 3, '22 at 5:56 am
Add to Discussion

Answers

0
Selected Answer

Hi and welcome to the Forum.

You declared datfilesToOpen as Variant so the file dialog will create an array (of file path strings) if one or more files are picked. If not (i.e. Cancel is pressed), the array is not initialized so this test will work:

If IsArray(datfilesToOpen) = False Then

        MsgBox "No file selected"

Else
On your second question, you did not include an embedded sample data file with your file above but this should work. In the revised file attached (and code extract below), I've changed the items in bold so that the file name only (from each datfile) is added to the file (with "¦¦¦" before it). That gets split by the .TextToColumns command (to fixed widths) so another loop reconstitues the file name (from all possibe slpit columns) then puts it  (e.g. "From :<<file name>>") in what becomes column A and colours the cell font red .
Sub ImportText_bckp()

    Dim fso As Object
    Dim qt As QueryTable
    Dim cn As Variant
    Dim datfilesToOpen As Variant, datfile As Variant


    Application.ScreenUpdating = False
    Set fso = CreateObject("Scripting.FileSystemObject")

    ' Opens folder to select files
    datfilesToOpen = Application.GetOpenFilename _
                (FileFilter:="Text Files (*.dat), *.dat", _
                MultiSelect:=True)

    If IsArray(datfilesToOpen) = False Then
        MsgBox "No file selected"
    Else

        ' Clears current entries
        If IsEmpty(Range("C4").Value) = False Then
            Range("C4").Select
            Range(Selection, Selection.End(xlToRight)).Select
            Range(Selection, Selection.End(xlDown)).Select
            Selection.ClearContents
        End If

        ' Inserts column for raw data entry
        Columns("A:A").Select
        Range("A3").Activate
        Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

            With ActiveSheet

                For Each datfile In datfilesToOpen


                    importrow = 1 + .Cells(.Rows.Count, 1).End(xlUp).Row
                    '' add  ¦¦¦ plus just the files name
                    Cells(importrow, 1).Value = "¦¦¦  From: " & Right(datfile, Len(datfile) - InStrRev(datfile, "\"))

                     With ActiveSheet.QueryTables.Add(Connection:= _
                    "TEXT;" & datfile, Destination:=.Cells(importrow + 1, 1))
                        .TextFileStartRow = 16
                        .TextFileParseType = xlFixedWidth
                        .TextFileTabDelimiter = True
                        .Refresh BackgroundQuery:=False
                        .AdjustColumnWidth = False
                     End With

                Next datfile

                For Each qt In ActiveSheet.QueryTables
                qt.Delete
                Next qt

                For Each cn In ThisWorkbook.Connections
                cn.Delete
                Next cn

            End With

            Range("A2").Select
            Range(Selection, Selection.End(xlDown)).Select
            Selection.TextToColumns Destination:=Range("D4"), DataType:=xlFixedWidth, _
            FieldInfo:=Array(Array(0, 1), Array(4, 1), Array(35, 1), Array(48, 1), Array(59, 1), _
            Array(65, 1), Array(76, 1)), TrailingMinusNumbers:=True

            ' find the ¦¦¦ files names, remove that can make text red
            For n = 1 To Cells(Rows.Count, 4).End(xlUp).Row
                If Cells(n, 4) = "¦¦¦" Then
                    'reform the file name
                    Cells(n, 2) = Cells(n, 5) & Cells(n, 6) & Cells(n, 7) & Cells(n, 8) & Cells(n, 9)
                    Range(Cells(n, 4), Cells(n, 9)).Value = ""
                    Cells(n, 2).Font.Color = vbRed
                End If
            Next n

            Columns("A:A").Delete Shift:=xlToLeft

            Columns("B:J").AutoFit
            Range("A4").Select

            MsgBox "Successfully imported .dat files", vbInformation, "SUCCESSFUL IMPORT"
    End If
Application.ScreenUpdating = True
End Sub
Further to your discussion below, the code above has been modified by changing this section (which finds "¦¦¦") to create/replace the MSN for the cells that follow and also then delete that particular line:
Dim MSN as string
.
.
.
    ' find the ¦¦¦ files names (count=Ubound), remove them then add MSN
    For n = 4 To Cells(Rows.Count, 4).End(xlUp).Row - UBound(datfilesToOpen)
        If Cells(n, 4) = "¦¦¦" Then
            'reform the file name
            Cells(n, 2) = Cells(n, 5) & Cells(n, 6) & Cells(n, 7) & Cells(n, 8) & Cells(n, 9)
            'Extract MSN
            MSN = Chr(39) & Mid(Cells(n, 2), 2, 4) 'assumes format "M*****.dat", add leading '
            Cells(n, 2).EntireRow.Delete 'delete row
            n = n - 1 'rewind counter for deletion
            Else 'write MSN
            Cells(n, 2) = MSN
        End If
        
    Next n
New file atttached.

Hope this works for you.

Discuss

Discussion

Hi John,

Firstly, thanks for the answering my first question. Of course, that makes sense to me now and it works like a charm!

Editing the original question to include Excel file and sample data files asap.

I would need .dat file names to be placed in the column A under MSN. Furthermore, if possible, I would only want to import part of the file name; starting at character 2 (just after "M") and in total 4 characters. For example a file named "M013514OCT211.dat" will only have 0135 imported in column A under MSN. And if possible I need this file name imported next to every line, so I know which message belongs to which MSN.
mkramar (rep: 2) Dec 8, '21 at 5:02 am
See my revised Answer. Sorry but I had not read the above (was busy testing my solution).
John_Ru (rep: 6142) Dec 8, '21 at 6:51 am
See newly revised Answer/ file which now writes MSN with a leading ' (so the leading 0 is displayed) and removes the lines (starting "¦¦¦") which captured the file names.
John_Ru (rep: 6142) Dec 8, '21 at 8:19 am
Hi John. I can't thank you enough! I owe you a beer - scrap that, I owe you a sixpack :D 

Thanks again and have a great rest of the day
mkramar (rep: 2) Dec 8, '21 at 10:52 am
Glad that worked for you. Thanks for selecting my Answer and the beers (though it's unlikely we'll ever meet / be in the same country).
John_Ru (rep: 6142) Dec 8, '21 at 11:10 am
Add to Discussion


Answer the Question

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