1

运行以下代码时,我收到一条错误消息,它发生在 rng = .Range.Copy From Recordset 行上。错误是“在 mscorlib.dll 中发生‘System.InvalidCastException’类型的第一次机会异常”。我知道这不是输出,因为注释掉的代码工作正常,尽管速度很慢。我正在研究一种加快速度的方法。这是代码

    Private Sub ButRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButRun.Click
    Dim DWPROD As String = "Data Source=DWPROD;User ID=gayloj01;password=jgay0421;"
    Dim Conn As New Oracle.DataAccess.Client.OracleConnection
    Dim cmd As New Oracle.DataAccess.Client.OracleCommand
    Dim ds As New DataSet
    Dim dtAdapter As New Oracle.DataAccess.Client.OracleDataAdapter
    Dim Excel As Microsoft.Office.Interop.Excel.Application
    Dim rng As Microsoft.Office.Interop.Excel.Range

    SQLBuilder()
    Conn.ConnectionString = DWPROD
    With cmd
        .Connection = Conn
        .CommandText = strSQL
        .CommandType = CommandType.Text
    End With
    dtAdapter.SelectCommand = cmd
    ds.Tables.Add("RawData")
    dtAdapter.Fill(ds, "RawData")
    Try
        Excel = CType(GetObject(, "Excel.Application"), Microsoft.Office.Interop.Excel.Application)
    Catch ex As Exception
        Excel = New Microsoft.Office.Interop.Excel.Application
    End Try
    Try
        With Excel
            .SheetsInNewWorkbook = 1
            .Workbooks.Add()
            .Worksheets(1).Select()
            .Visible = True
            .ScreenUpdating = False
            rng = .Range(.Cells(1, 1), .Cells(ds.Tables("RawData").Rows.Count, ds.Tables("RawData").Columns.Count))
            rng.CopyFromRecordset(ds.Tables("RawData"), ds.Tables("RawData").Rows.Count, ds.Tables("RawData").Columns.Count)
            'Dim i As Integer = 1
            'For col = 0 To ds.Tables("RawData").Columns.Count - 1
            '.Cells(1, i).value = ds.Tables("RawData").Columns(col).ColumnName
            '.Cells(1, i).EntireRow.Font.Bold = True
            'i += 1
            'Next
            'i = 2
            'Dim j As Integer = 1
            'For col = 0 To ds.Tables("RawData").Columns.Count - 1
            'i = 2
            'For row = 0 To ds.Tables("RawData").Rows.Count - 1
            '.Cells(i, j).Value = ds.Tables("RawData").Rows(row).ItemArray(col)
            'i += 1
            'Next
            'j += 1
            'Next
            .ScreenUpdating = True
        End With
    Catch ex As Exception
        Debug.Print(ex.Message)
    End Try

End Sub

我认为这与我如何填充范围有关,但我找不到任何问题。我对 VB.net 很陌生,如果能提供任何帮助,我将不胜感激。

TIA

吉姆·G

4

1 回答 1

5

调试时会发生第一次机会异常,这是 .NET Framework 为调试器(即 Visual Studio)提供处理问题的机会的方式。如果调试器无法解决第一次机会异常,那么它将成为您的代码应处理的异常。如果您的代码不处理异常,那么最终.NET Framework 将处理它(即ASP.NET 中的黄屏死机)。

您可以忽略第一次机会异常,因为它们是为调试器准备的。换句话说,您的异常代码(try-catch逻辑)不会让您与第一次机会异常进行交互。

于 2013-08-20T17:54:15.383 回答