将txt转换为xls

时间:2018-12-11 12:41:45

标签: excel vba

我有代码可以从txt文件中复制信息,并将其放置在xlsm文件中,并按一定的行数分割,然后继续下一个工作表(该txt文件有超过200万行)。

我遇到的问题是,它不会复制前700,000行,但会复制其余行,而且在第一个工作表中,它会粘贴中文,我不确定这是否与来自txt的信息有关文件。有人可以指出我哪里出了问题吗?

Sub SplitTxt_01()

Const HelperFile As String = "ABCD" 
Const N As Long = 699998  
Dim myPath
 myPath = "D:\Test\" 
Dim myFile
 myFile = "20181129_EXPORT_RESULTS.txt" 

Dim WB As Workbook, myWB As Workbook
 Set myWB = ThisWorkbook
Dim myWS As Worksheet
Dim t As Long, r As Long
Dim myStr

Application.ScreenUpdating = False


myFile = Dir(myPath & myFile)
Open myPath & myFile For Input As #1
t = 1
r = 1
Do While Not EOF(1)
    Line Input #1, myStr
    If r > N Then
        t = t + 1
        r = 1
    End If
    Open myPath & HelperFile & t & ".txt" For Append As #2
    Print #2, myStr
    Close #2
    r = r + 1
Loop
Close #1

For i = t To 1 Step -1
    Workbooks.OpenText Filename:=myPath & HelperFile & i & ".txt", DataType:=xlDelimited, Tab:=True
    Set WB = ActiveWorkbook
    Set Rng = ActiveSheet.UsedRange
    Set myWS = myWB.Sheets.Add
    myWS.Name = HelperFile & i
    Rng.Copy myWS.Cells(1, 1)
    WB.Close False
Next
myWB.Save

Set Fso = CreateObject("Scripting.FileSystemObject")
Set Fldr = Fso.GetFolder(myPath)

For Each Filename In Fldr.Files
    If Filename Like "*" & HelperFile & "*" Then Filename.Delete
Next

Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:0)

您将N设置为699998, 然后进行测试,如果r

因此,只有在r大于N之后,它才会开始复制行。

至少我是这样阅读的...