1

多数のテキスト ファイルからデータ行を Excel シートにインポートするための回答を見つけました ( https://stackoverflow.com/a/4941605/1892030 Chris Neilsen が回答)。ただし、次のことも行いたいと思います。

  1. インポートしたい有用なデータの前後にガベージ データがあります。インポートしたいデータ行はすべてアスタリスク (*) で始まります。
  2. データはコンマで区切られているため、Excel にインポートするときにそのように解析する必要があります。これは、上記の回答の解析コードを編集することで変更できます。
  3. インポートされる各行の最後に、データのインポート元のテキスト ファイルの名前 (ファイル名のみ、ファイル拡張子なし) であるデータ項目を追加したいと考えています。

上記の Chris からの回答は非常にうまく機能するので、上記の 1 と 3 の追加要件を考慮してコードを編集したいと思いますが、方法がわかりません。完全を期すために、以下の以前の回答からコードをコピーします。どうもありがとう。

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:\#test")

    ' 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 comma 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
4

1 に答える 1

0

すべてを行ったわけではありませんが (必要な形式に合わせてファイル名を整理する必要があると思います)、このコードをドロップすると、開始できます...

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

        TextLine = FileText.ReadLine

        ' Process lines which don't begin with Asterisk (*)
        If Left(TextLine,1)<>"*" Then 

            ' This crudely appends the filename as if it were a column in the source file
            TextLine = TextLine + "," + file.Name

            ' Parse the line into comma 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)
        End If
    Loop
于 2012-12-11T17:56:42.120 に答える