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