导入多个文本文件

时间:2015-11-24 17:29:35

标签: excel vba import

我在目录中有多个文本文件(.hne文件),我想将数据导入Excel,但只导入第11行之后的数据。下面的代码导入数据,但它只能在一个文件中执行一个时间和我的文本文件有四列用空格分隔,当它导入Excel时,它将所有列放在一列中。

有人可以帮我清理一下这段代码我一定很感激。此外,我有很多文本文件,它可能会超过一个活动表中的最大行,因为它可能会自动将其余数据放在另一个工作表上。

Private Sub()
Dim FilePath As String
Dim i, j As Integer
i = 0
j = 1

FilePath = ThisWorkbook.Path & "\201412010030.hne"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(FilePath, 1)
Do Until objFile.AtEndOfStream
    strline = objFile.ReadLine
    'If objFile.AtEndOfStream = True Then
        'MsgBox strLine
    'End If
    i = i + 1
    If i > 11 Then
        Cells(j, 1).Value = strline
        j = j + 1
    End If
Loop
objFile.Close

End Sub

以下是我尝试导入的文件的示例

   TRIAXYS BUOY DATA REPORT - TAS05642
   VERSION  = 6a.02.08
   TYPE = HNE
   DATE = 2014 Dec 01 01:00
   NUMBER OF POINTS =    2072
   TIME OF FIRST POINT (s)  =   90.63
   SAMPLE INTERVAL (s)  =    0.78
   COLUMN 1 = TIME (s)
   COLUMN 2 = HEAVE (m)
   COLUMN 3 = DSP NORTH (m)
   COLUMN 4 = DSP EAST (m)
   90.63  -0.42   0.53  -0.34
   91.41   0.14   0.72  -0.39
   92.19   0.45   0.61  -0.47
   92.98   0.75   0.26  -0.11
   93.76   1.04  -0.26   0.53
   94.54   0.58  -0.68   0.94
   95.32  -0.13  -0.67   1.00
   96.10  -0.26  -0.47   0.90
   96.88  -0.50  -0.31   0.50
   97.66  -0.94  -0.22  -0.14

下面这段代码效果很好,我唯一要做的就是导入第11行之后的所有数据。

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

' 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, " ")

        ' Put data on one row in active sheet
       cl.Resize(1, UBound(Items) - LBound(Items) + 1).Value = Items

        ' 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

0 个答案:

没有答案