這是我正在使用的代碼,其工作正常,但僅適用於一行。我需要將它應用於文本文件的所有行。我在文本文件中總共有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
使用'斯普利特(myStr中,vbCrLf)'(或者換行分隔符)將文件內容分割成線的陣列,然後在該數組迴路和過程類似於你在做什麼已經每條線爲第一線做準備。增加Excel中每行的行數。 –