2017-10-05 63 views
1

這是我正在使用的代碼,其工作正常,但僅適用於一行。我需要將它應用於文本文件的所有行。我在文本文件中總共有150行。我如何循環它,並將下一行作爲記錄的結尾。Excel宏,用於將固定長度文本文件轉換爲用字符串分隔的分隔符

代碼:

Public Sub Convert_TxtFile() 
Dim myStr As String 
    myStr = FileText("C:\Users\BS255028\Desktop\Book2.txt") 
    Cells(1, 1) = Mid(myStr, 1, 4) 
    Cells(1, 2) = Mid(myStr, 5, 3) 
    Cells(1, 3) = Mid(myStr, 8, 8) 
    Cells(1, 4) = Mid(myStr, 16, 2) 
    End Sub 

    Function FileText(ByVal filename As String) As String 

    Dim nFileNum As Integer 

    If Len(Dir$(filename)) = 0 Then 
     Err.Raise 53 
    End If 

    nFileNum = FreeFile 
    Open filename$ For Binary As #nFileNum 
    FileText = Space$(LOF(nFileNum)) 
    Get #nFileNum, , FileText 
    Close #nFileNum 

    End Function 
+0

使用'斯普利特(myStr中,vbCrLf)'(或者換行分隔符)將文件內容分割成線的陣列,然後在該數組迴路和過程類似於你在做什麼已經每條線爲第一線做準備。增加Excel中每行的行數。 –

回答

1

您可以簡單地記錄導入文本文件的宏。使用固定寬度將允許您根據所需的寬度將文本分成多列。

With ActiveSheet.QueryTables.Add(Connection:= _ 
    "TEXT;C:\Users\BS255028\Desktop\Book2.txt", _ 
    Destination:=Range("$A$1")) 
    .Name = "adam_styborskis_pauper_cube" 
    .FieldNames = True 
    .RowNumbers = False 
    .FillAdjacentFormulas = False 
    .PreserveFormatting = True 
    .RefreshOnFileOpen = False 
    .RefreshStyle = xlInsertDeleteCells 
    .SavePassword = False 
    .SaveData = True 
    .AdjustColumnWidth = True 
    .RefreshPeriod = 0 
    .TextFilePromptOnRefresh = False 
    .TextFilePlatform = 437 
    .TextFileStartRow = 1 
    .TextFileParseType = xlFixedWidth 
    .TextFileTextQualifier = xlTextQualifierDoubleQuote 
    .TextFileConsecutiveDelimiter = False 
    .TextFileTabDelimiter = True 
    .TextFileSemicolonDelimiter = False 
    .TextFileCommaDelimiter = False 
    .TextFileSpaceDelimiter = False 
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1) 
    .TextFileFixedColumnWidths = Array(4, 3, 8, 2) 
    .TextFileTrailingMinusNumbers = True 
    .Refresh BackgroundQuery:=False 
End With 
+0

感謝它工作完美。 –

0

不知道如何FileText作品,但如果它把文本在Excel中150行,你可以再補充一個循環:

Public Sub Convert_TxtFile() 
Dim myStr As String 
Dim i as Long 

myStr = FileText("C:\Users\BS255028\Desktop\Book2.txt") 
For i = 1 to 150 
    Cells(i, 1) = Mid(myStr, 1, 4) 
    Cells(i, 2) = Mid(myStr, 5, 3) 
    Cells(i, 3) = Mid(myStr, 8, 8) 
    Cells(i, 4) = Mid(myStr, 16, 2) 
Next i 
End Sub 
1

未經測試:

Public Sub Convert_TxtFile() 
    Dim myStr As String, s, arr, i As Long 
    myStr = FileText("C:\Users\BS255028\Desktop\Book2.txt") 
    arr = Split(myStr, vbCrLf) 
    i = 1 
    for each s in arr 
     Cells(i, 1).Resize(1, 4) = Array(Mid(myStr, 1, 4), Mid(myStr, 5, 3), _ 
             Mid(myStr, 8, 8), Mid(myStr, 16, 2)) 
     i = i + 1 
    next 

End Sub 
相關問題