คุณ beerku ลองดูตามไฟล์แนบนี้นะครับ
ผมเขียน VBA โดยการ record macro จากการใช้ function import data นี่แหละครับ แล้วเพิ่มเติมในส่วนของ การค้นหาไฟล์ .txt ทั้งหมด ใน folder ที่กำหนด ว่ามีกี่ไฟล์ จากนั้น ก็จัดการ import data ใน text file นั้น มาเรียงใน cell ที่ต้องการ
สิ่งที่คุณต้องทำคือ เปลี่ยน ชื่อ folder ที่เก็บ ไฟล์ เป็นของคุณเอง โดยใน code ให้เปลี่ยนบรรทัดที่เขียนว่า .LookIn = "C:\Data_Folder" ให้เปลี่ยนเป็นที่อยู่ folder ของคุณเอง
ถ้าคุณเรียก folder ผิด หรือ ไม่มี ไฟล์ .txt อยู่ใน folder นั้น ตัวโปรแกรมก็จะแจ้งว่าไม่เจอไฟล์นะครับ
สงสัย code ส่วนไหน ทำงานอย่างไร ก็สอบถามได้นะครับ
Code:
Sub GetFile()
Columns("A:D").Select
Selection.ClearContents
Range("A1").Select
Set fs = Application.FileSearch
Dim path As String
With fs
.LookIn = "C:\Data_Folder"
.Filename = "*.txt"
If .Execute > 0 Then
MsgBox "There were " & .FoundFiles.Count & _
" file(s) found."
For i = 1 To .FoundFiles.Count
path = .FoundFiles(i)
'==============
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & path, _
Destination:=Range("A" & i + 1))
.Name = "DataSheet"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 874
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
'==============
Next i
Else
MsgBox "There were no files found."
End If
End With
End Sub