Excel宏用于将修复长度文本文件转换为用子字符串函数分隔的分隔符

时间:2017-10-05 04:42:39

标签: excel vba excel-vba

这是我正在使用的代码,它的工作正常但仅限于一行。我需要将它应用于文本文件的所有行。我在文本文件中总共有150行。如何循环它将下一行作为记录的结尾。

代码:

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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