2

したがって、この Excel マクロは、特定のフォルダーから複数の txt ファイルを読み取り、すべての行を最初の Excel シートに挿入するのに最適です。マクロがすべてのtxtファイルの最初の行をスキップするように、このコードを編集したいと思います..

誰でも助けることができますか?

Sub test1()
    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\Desktop\TXT")

    ' set the starting point to write the data to
    Set cl = ActiveSheet.Cells(1, 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, vbTab)

            ' Put data on one row in active sheet
            cl.Value = file.Name
            ' Put data on one row in active sheet
            For i = 0 To UBound(Items)
                cl.Offset(0, i + 1).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
4

1 に答える 1

2

オプション 1 最初の行を事前に読む

Do While ループを開始する前に、次の行を追加します。

If Not FileText.AtEndOfStream Then TextLine = FileText.ReadLine

このようにして、最初の行 (存在する場合) を読み取り、Do While ループは後続の行のみを読み取ります。

オプション 2 後で Excel の最初の行を削除する

別の解決策は、スクリプトがすべてのファイルのインポートを完了した後で、Excel の最初の行を削除することです。

アクティブなインポートが唯一のものであるかどうかわからないため、これがどの列に適用されるかを特定する必要があるかもしれません (そうしないと、以前にインポートされた値を削除する必要があります。

于 2013-04-30T16:15:46.487 に答える