Excelmacros,用于将固定长度文本文件转换为用substring函数分隔的分隔符

这是我正在使用的代码,它的工作正常,但只有一行。我需要使它通用,将其应用于文本文件的所有行。我有总共150行的文本文件。如何循环它,而制作下一行作为logging的结尾。

码:

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 

你可以简单地logging你导入文本文件的macros。 使用固定的宽度将允许您根据所需的宽度将文本分割成列。

 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 

未经testing:

 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 

不知道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