使用Tab作为分隔符,并在一个空行开始一个新的工作表
我有一个脚本来将文本文件导入到Excel中。
目标是使用制表符作为分隔符,并在一个空行,开始一个新的工作表。
目前的问题是脚本为每一行开始一个新的工作表。
我是否需要用不同的方式来解释空行? 其他尝试解释和处理表单成功更改,从导入的数据中删除空格,然后分隔符是无效的。
Public Sub ImportTextFile(FName As String, Sep As String) Dim RowNdx As Long Dim ColNdx As Integer Dim TempVal As Variant Dim WholeLine As String Dim Pos As Integer Dim NextPos As Integer Dim SaveColNdx As Integer Dim WS As Worksheet Dim SheetNumber As Long Const C_START_SHEET_NAME = "Sheet1" SheetNumber = 1 RowNdx = C_START_ROW_FIRST_PAGE Set WS = ActiveWorkbook.Worksheets(C_START_SHEET_NAME) Application.ScreenUpdating = False SaveColNdx = ActiveCell.Column RowNdx = ActiveCell.Row Open FName For Input Access Read As #1 While Not EOF(1) Line Input #1, WholeLine 'This section added to create new sheets for empty lines If InputLine = "" Then SheetNumber = SheetNumber + 1 Set WS = ActiveWorkbook.Worksheets.Add(after:=WS) RowNdx = 1 End If If Right(WholeLine, 1) <> Sep Then WholeLine = WholeLine & Sep End If ColNdx = SaveColNdx Pos = 1 NextPos = InStr(Pos, WholeLine, Sep) While NextPos >= 1 TempVal = Mid(WholeLine, Pos, NextPos - Pos) Cells(RowNdx, ColNdx).Value = TempVal Pos = NextPos + 1 ColNdx = ColNdx + 1 NextPos = InStr(Pos, WholeLine, Sep) Wend RowNdx = RowNdx + 1 SheetNumber = SheetNumber + 1 Wend EndMacro: On Error GoTo 0 Application.ScreenUpdating = True Close #1 End Sub
您正在读入WholeLine
,然后testingInputLine
添加Option Explicit
会捕捉这样的事情。