Visual Basic代码过早结束

时间:2018-08-09 03:37:47

标签: excel vba excel-vba

我正在修改Visual Basic代码以将CSV文件导入Excel。代码过早地结束而没有做应做的事情。调试显示,在ws.name = line行,它仅跳过其余代码,并跳至End Sub。这是什么问题?

代码如下:

Sub ImportData()

    readCSV ActiveWorkbook.Path & "\output.txt", "vbTab"

End Sub

Private Sub readCSV(parFileName As String, parDelimiter As String)

    Dim i As Long
    Dim j As Long
    Dim locNumCols As Long
    Dim fso As Variant
    Dim ts As Variant
    Dim line As Variant
    Dim lineSplit As Variant

    Set fso = CreateObject("Scripting.FileSystemObject")

    On Error GoTo error_open_file
    Set ts = fso.OpenTextFile(parFileName)
    On Error GoTo unhandled_error

    i = 1
    j = 1
    locNumCols = 0
    Do While Not ts.AtEndOfStream
        line = ts.ReadLine
        If InStr(line, "New Sheet ") <> 0 Then
            Dim ws As Worksheet
            With ThisWorkbook
                Set ws = .Sheets.Add(After:=.Sheets(.Sheets.Count))
            End With
            ws.name = line
            ws.Activate
            i = 1
            j = j + locNumCols
            locNumCols = 0
        Else
            lineSplit = Split(line, parDelimiter)
            ActiveSheet.Cells(i, j).Resize(1, UBound(lineSplit, 1)) = lineSplit
            If locNumCols < UBound(lineSplit, 1) Then
                locNumCols = UBound(lineSplit, 1)
            End If
            i = i + 1
        End If
    Loop

    ts.Close

error_open_file:             'returns empty variant
unhandled_error:             'returns empty variant

End Sub

3 个答案:

答案 0 :(得分:1)

我添加了以下几行来打印错误:

unhandled_error:

    Dim Msg
    If Err.Number <> 0 Then
        Msg = "Error # " & Str(Err.Number) & " was generated by " & Err.Source & Chr(13) & Err.Description
        MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
    End If

结果是该字符串超出了工作表名称的长度。感谢@chrisneilsen指出了这一点!

答案 1 :(得分:0)

readCSV ActiveWorkbook.Path & "\output.txt", "vbTab"

应该是

readCSV ActiveWorkbook.Path & "\output.txt", vbTab

除非数据不是由制表符分隔的,而是按字面意思是“ vbTab”(尽管您说的是CSV,所以...)

这可能会在这里引发错误:

lineSplit = Split(line, parDelimiter)
ActiveSheet.Cells(i, j).Resize(1, UBound(lineSplit, 1)) = lineSplit

如果没有定界符,则lineSplit的UBound为零,并且您不能将列的大小调整为零...

答案 2 :(得分:0)

如果您刚刚读入Line的文本不是有效的工作表名称,则错误处理程序将触发并跳至unhandled_error:标签(实际上是 next 行将以单步模式突出显示,这就是为什么它似乎跳到End Sub

如果您不能保证源数据的有效性,则您的代码需要处理可能的错误,如下所示。 (我留给您决定如何处理失败的)

On Error Resume Next
    ws.Name = line
On Error GoTo unhandled_error
If ws.Name <> line Then
    ' That Failed.  What now?
Else
    ' Carry On

End If

旁注,如Tim所言,您的Split逻辑存在问题。 Split返回基于0的1D数组,因此UBound(lineSplit)line被分割的部分数少1。

ActiveSheet.Cells(i, j).Resize(1, UBound(lineSplit, 1)) = lineSplit不会粘贴lineSplit中的最后一个值。如果line

中没有定界符,则会出现运行时错误