I've been googling around on ways to import multiple text files without just specifying the directory in the macro. I sort of tried to combine two codes together, one that lets me select the text files, and one that lets me put all the data onto one spreadsheet, but it's not working. Any ideas?
I get a type mismatch error
Code:
Sub CombineTextFiles()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
Dim myDir As String, fn As String, txt As String, y, delim As String
Dim a(), n As Long, t As Long, maxCol As Integer
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
ReDim a(1 To Rows.Count, 1 To Columns.Count)
delim = vbTab
fn = Dir(FilesToOpen & "\*.txt")
Do While fn <> ""
txt = CreateObject("Scripting.FileSystemObject").OpenTextFile(FilesToOpen & "\" & fn).ReadAll
x = Split(Replace(txt, vbCrLf, delim), delim): t = t + 1: n = 1
a(t, n) = fn
For i = 0 To UBound(y)
n = n + 1: a(t, n) = y(i)
Next
maxCol = Application.Max(maxCol, n)
fn = Dir
Loop
ThisWorkbook.Sheets(1).Range("a1").Resize(t, maxCol).Value = a
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
I get a type mismatch error