我有一個文件夾中的多個txt文件,這些文件是製表符分隔的。這些文件中的每一個文件都有一個名爲EngagementId的列,它是相同的值,與記錄數無關。但是,它會更改每個txt文件,這是我想要捕獲的。使用VBA從多個文本文件中只讀取一條記錄到Excel中
- 我想獲取第一行的文件名。該GetFileNames()的作品爲(在評論中指出)
Sub GetFileNames()
Dim sPath As String
Dim sFile As String
Dim iRow As Integer
Dim iCol As Integer
Dim splitFile As Variant
'specify directory to use - must end in "\"
sPath = ActiveWorkbook.Path
iRow = 0
sFile = Dir(sPath & "\Individual Reports\")
Do While sFile <> ""
iRow = iRow + 1
splitFile = Split(sFile, ".txt")
For iCol = 0 To UBound(splitFile)
Sheet1.Cells(iRow, iCol + 1) = splitFile(iCol)
Next iCol
sFile = Dir ' Get next filename
Loop
End Sub
每個txt文件中有一列(這是在第13位在每個文本文件),稱爲「EngagementId」。我只想拉第一行「Engagement Id」,它來自第二行(因爲第一行包含標題)。
Sub Extractrec()
Dim filename As String, nextrow As Long, MyFolder As String
Dim MyFile As String, text As String, textline As String
MyFolder = ActiveWorkbook.Path
MyFile = Dir(MyFolder & "\Individual Reports\*.txt")
Do While MyFile <> ""
Open (MyFolder & MyFile) For Input As #1
Do Until EOF(1)
Line Input #1, LineFromFile
LineItems = Split(LineFromFile, "\t") 'second loop text is already stored
'-> see reset text
Sheet1.Cells(iRow, iCol + 2).Value = LineItems(13, 2)
Loop
Close #1
Loop
什麼問題?我不確定「\ t」在vba中有效,我會使用vbtab常量。 – Jules
你在向我們展示什麼 - 你有沒有按你想要的方式工作的代碼 - 它現在吐出了什麼 - 以及應該如何改變?示例數據有助於 - 這兩個單獨的函數是否會從別處調用? – dbmitch
'Sheet1.Cells(iRow,iCol + 2).Value = LineItems(13,2)'將成爲下標超出範圍的錯誤 - 「Split」返回一維數組。 – Comintern