VBA逐行读取txt文件并将每行保存到新的Excel工作表

时间:2015-10-26 16:36:21

标签: excel vba

我有一个txt文件,其中包含多个原始文件(> 1000)。我想逐行读取此文件,并每次将它们复制到新的Excel工作表(单元格A1)。 txt文件的每个原始文件都包含excel公式,用于通过Internet从财务数据库生成数据请求。所以每次它必须从数据库中提取数据。我试图自己编写代码,我尝试了两种可能性来逐行读取数据,但是我得到了该行的错误消息,我将该行写入单元格:

Sheet_i.Cells(1, 1).Value = TextLine    

我不明白,我在哪里弄错了。

这是我的第一个代码,它使用fso:

Sub ReadtxtFileIntoSeveralSheets()

Dim fso As FileSystemObject: Set fso = New FileSystemObject
Dim txtStream As TextStream
Dim TextLine As String
Dim i As Long 
Dim Sheet_i As Worksheet

' Get a FileSystem object
Set fso = New FileSystemObject

' get the file you want
Set txtStream = fso.OpenTextFile("D:\excel\formula.txt", ForReading, False)

i = 0 'to offset column for each line

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

    TextLine = txtStream.ReadLine 'read line
    ' create new active worksheet

    Set Sheet_i = Worksheets.Add(after:=Worksheets(Worksheets.Count))
    'paste the line to A1

     Sheet_i.Cells(1, 1).Value = TextLine

    i = i + 1
Loop

' Close file
txtStream.Close


Set txtStream = Nothing
Set fso = Nothing

End Sub

这是我的第二个代码:

Sub Data_copy_several_sheets_2()

Dim FileNum As Integer
Dim DataLine As String
Dim Sheet_i As Worksheet

FileNum = FreeFile()
Open "D:\excel\formula.txt" For Input As #FileNum

 While Not EOF(FileNum)
    Line Input #FileNum, DataLine ' read in data 1 line at a time
    Set Sheet_i = Worksheets.Add(after:=Worksheets(Worksheets.Count))

    Sheet_i.Cells(1, 1).Value = DataLine 'fill cell

 Wend
 Close #FileNum
End Sub

有人可以帮助我完成这项任务吗?

1 个答案:

答案 0 :(得分:0)

Sheet_i.Cells(1, 1).Value = DataLine 

应该是

Sheet_i.Cells(1, 1).Formula = DataLine

您可能还想修剪该行并删除任何多余的空格以确保安全:

Sheet_i.Cells(1, 1).Formula = Trim(DataLine)

如果您仍未到达任何地方,请确保正确的应用程序设置:

Sub SwitchOnDefaults()
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .DisplayAlerts = True
        .Calculation = xlCalculationAutomatic
    End With
End Sub