【问题标题】:Import the 2nd row of multiple text files into Excel将多个文本文件的第二行导入 Excel
【发布时间】:2017-06-30 15:23:24
【问题描述】:

我想将文件夹中多个制表符分隔的文本文件的第二行导入到 Excel 中,从第 2 行开始。

我已经记录了一个宏,它从第 2 行开始将单个制表符分隔的文本文件的第 2 行导入到 excel 中。(我在 excel 表中有一个标题行)。我还找到了将多个文本文件导入 excel 的代码。我很难把它们放在一起。我想将多文件导入功能添加到我录制的宏中。

这是我记录的将单个文本文件的第二行导入到 Excel 中的第 2 行的代码。我希望这段代码将多个文本文件的第二行导入 Excel,从第 2 行开始,然后是第 3 行等...

Sub Import()
'
' Import Macro
'

'
With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;C:\Users\t830439\Desktop\test\BTWP004217_2017_6_29_12'14'03'0001.upl", _
    Destination:=Range("$A$2"))
    .CommandType = 0
    .Name = "BTWP004217_2017_6_29_12'14'03'0001"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 65001
    .TextFileStartRow = 2
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierNone
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = True
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 _
    , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
End Sub

这里是导入多个文本文件的代码。我需要在上面记录的代码中添加“遍历所有文件”功能。我已经为该代码添加了正确的参考来运行。

Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range

' Get a FileSystem object
Set fso = New FileSystemObject

' get the directory you want
Set folder = fso.GetFolder("C:\Users\t830439\Desktop\test")

' set the starting point to write the data to
Set cl = ActiveSheet.Cells(2, 1)

' Loop thru all files in the folder
For Each file In folder.Files
    ' Open the file
    Set FileText = file.OpenAsTextStream(ForReading)

    ' Read the file one line at a time
    Do While Not FileText.AtEndOfStream
        TextLine = FileText.ReadLine

        ' Parse the line into | delimited pieces
        Items = Split(TextLine, "|")

        ' Put data on one row in active sheet
        For i = 0 To UBound(Items)
            cl.Offset(0, i).Value = Items(i)
        Next

        ' Move to next row
        Set cl = cl.Offset(1, 0)
    Loop

    ' Clean up
    FileText.Close
Next file

Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing

End Sub

谢谢。

编辑 - 更新--------------------------------------------------------

我已合并代码,但无法将其放入 Loop。

Sub ReadFilesIntoActiveSheet3()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range

' Get a FileSystem object
Set fso = New FileSystemObject

' get the directory you want
Set folder = fso.GetFolder("C:\Users\t830439\Desktop\test")

' set the starting point to write the data to
Set cl = ActiveSheet.Cells(2, 1)

' Loop thru all files in the folder
For Each file In folder.Files
    ' Open the file
    Set FileText = file.OpenAsTextStream(ForReading)

    ' Read the file one line at a time
    Do While Not FileText.AtEndOfStream
        TextLine = FileText.ReadLine

        ' Parse the line into | delimited pieces
        'Items = Split(TextLine, "|")

        ' Put data on one row in active sheet
      '  For i = 0 To UBound(Items)
         '  cl.Offset(0, i).Value = Items(i)
       ' Next

        'Move to next row
        Set cl = cl.Offset(1, 0)



     With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;C:\Users\t830439\Desktop\test\BTWP004217_2017_6_29_12'14'03'0001.upl", _
    Destination:=Range("$A$2"))
   ' .CommandType = 0
    .Name = "BTWP004217_2017_6_29_12'14'03'0001"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 65001
    .TextFileStartRow = 2
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierNone
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = True
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 _
    , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With

    Loop

    ' Clean up
    FileText.Close
Next file

Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing

End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    这个怎么样?

    Sub Basic_Example_1()
        Dim MyPath As String, FilesInPath As String
        Dim MyFiles() As String
        Dim SourceRcount As Long, Fnum As Long
        Dim mybook As Workbook, BaseWks As Worksheet
        Dim sourceRange As Range, destrange As Range
        Dim rnum As Long, CalcMode As Long
    
        'Fill in the path\folder where the files are
        MyPath = "C:\Users\Ron\test"
    
        'Add a slash at the end if the user forget it
        If Right(MyPath, 1) <> "\" Then
            MyPath = MyPath & "\"
        End If
    
        'If there are no Excel files in the folder exit the sub
        FilesInPath = Dir(MyPath & "*.xl*")
        If FilesInPath = "" Then
            MsgBox "No files found"
            Exit Sub
        End If
    
        'Fill the array(myFiles)with the list of Excel files in the folder
        Fnum = 0
        Do While FilesInPath <> ""
            Fnum = Fnum + 1
            ReDim Preserve MyFiles(1 To Fnum)
            MyFiles(Fnum) = FilesInPath
            FilesInPath = Dir()
        Loop
    
        'Change ScreenUpdating, Calculation and EnableEvents
        With Application
            CalcMode = .Calculation
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
        End With
    
        'Add a new workbook with one sheet
        Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
        rnum = 1
    
        'Loop through all files in the array(myFiles)
        If Fnum > 0 Then
            For Fnum = LBound(MyFiles) To UBound(MyFiles)
                Set mybook = Nothing
                On Error Resume Next
                Set mybook = Workbooks.Open(MyPath & MyFiles(Fnum))
                On Error GoTo 0
    
                If Not mybook Is Nothing Then
    
                    On Error Resume Next
    
                    With mybook.Worksheets(1)
                        Set sourceRange = .Range("A2:AA2")
                    End With
    
                    If Err.Number > 0 Then
                        Err.Clear
                        Set sourceRange = Nothing
                    Else
                        'if SourceRange use all columns then skip this file
                        If sourceRange.Columns.Count >= BaseWks.Columns.Count Then
                            Set sourceRange = Nothing
                        End If
                    End If
                    On Error GoTo 0
    
                    If Not sourceRange Is Nothing Then
    
                        SourceRcount = sourceRange.Rows.Count
    
                        If rnum + SourceRcount >= BaseWks.Rows.Count Then
                            MsgBox "Sorry there are not enough rows in the sheet"
                            BaseWks.Columns.AutoFit
                            mybook.Close savechanges:=False
                            GoTo ExitTheSub
                        Else
    
                            'Copy the file name in column A
                            With sourceRange
                                BaseWks.Cells(rnum, "A"). _
                                        Resize(.Rows.Count).Value = MyFiles(Fnum)
                            End With
    
                            'Set the destrange
                            Set destrange = BaseWks.Range("B" & rnum)
    
                            'we copy the values from the sourceRange to the destrange
                            With sourceRange
                                Set destrange = destrange. _
                                                Resize(.Rows.Count, .Columns.Count)
                            End With
                            destrange.Value = sourceRange.Value
    
                            rnum = rnum + SourceRcount
                        End If
                    End If
                    mybook.Close savechanges:=False
                End If
    
            Next Fnum
            BaseWks.Columns.AutoFit
        End If
    
    ExitTheSub:
        'Restore ScreenUpdating, Calculation and EnableEvents
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
            .Calculation = CalcMode
        End With
    End Sub
    

    https://www.rondebruin.nl/win/s3/win008.htm

    【讨论】:

    • 这很接近。我成功删除了“将文件名复制到 A 列”,现在字符串从 A 列开始。我需要以下帮助:1. 将文本导入为制表符分隔 2. 导入活动工作表,而不是新工作表
    • 好的,对于#2,更改这一行: Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1) 它应该是这样的: Set BaseWks = Worksheets("Sheet1") OR Set BaseWks = ActiveSheet 我认为...您可以尝试看看它是否有效。至于#1 ...嗯...我不确定。当您以这种方式执行此过程时,我什至没有意识到这是一个问题。
    • 好的,我会尝试,我会尝试创建另一个宏来将 A 列转换为分隔文本。
    • 两个建议都有效。此外,我录制了“文本到列”宏并将其添加到 BaseWks.Columns.AutoFit 的上方,效果很好!!!感谢您的帮助!!!!!!
    • 乐于助人。在您前进的过程中,请对这些事情保持开放的态度。有时存在内存限制,例如 Excel 中的 1,048,576 行限制,但实际上,您可以使用技术做的事情没有限制。也许唯一的限制是你自己的想象力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2016-04-17
    • 2015-03-08
    相关资源
    最近更新 更多