在同一工作表上将多个文本文件导入单独的Excel行

时间:2018-03-29 13:13:34

标签: excel vba

我有大约50个文本文件,它们都包含10-25行之间的任何内容,

我正在寻找一种方法将所有50个文本文件导入到一个Excel工作表中,每个文本文件内容都会进入一行。

因此,对于50个文本文件,我希望50行文本包含每行10-25行之间的任何内容。

1 个答案:

答案 0 :(得分:0)

对于我假设的解决方案,您有一个要读取的文件的文件路径列表。 为了实现您想要的结果,我建议将每个文件的输入流传递给String变量,并将它们存储在具有多个输入文件长度的数组中。最后,您可以将Array写入Range。因此,一个单元格将包含在单元格内分割成行的每个输入文件的内容。

Sub readTxtFiles(filePathList As Variant)
Dim strFileContent As String
Dim iFile As Integer: iFile = FreeFile
'Array with length of number of input files
Dim contentArray As Variant
ReDim contentArray(UBound(filePathList))

i = 0
For Each filePath In filePathList
    'Open file and store content to strFileContent and close file
    Open filePath For Input As #iFile
    strFileContent = Input(LOF(iFile), iFile)
    Close #iFile
    'Store content in output array 
    contentArray(i) = strFileContent
    'Clear content variable and increment i
    strFileContent = ""
    i = i + 1
Next filePath

ThisWorkbook.Sheets(1).Range("A1:A"& Ubound(filePathList)) = contentArray
End Sub

编辑:

由于文件位置也存储在文件中,因此您可以使用以下代码将其传递给找到的here

数组
Function readPathList(path as String) As Variant
    Dim sFile As String, sWhole As String
    Dim v As Variant
    sFile = "C:\mytxtfile.txt"
    Open sFile For Input As #1
    sWhole = Input$(LOF(1), 1)
    Close #1
    v = Split(sWhole, vbNewLine)
    readPathList= v
End Function

然后致电

readTxtFiles(readPathList('Path to your list'))