我在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
Jim G
答案 0 :(得分:5)
在调试时会发生第一次机会异常,并且.NET Framework为调试器(即Visual Studio)提供处理问题的机会。如果调试器无法解决第一次机会异常,那么它将成为您的代码应该处理的异常。如果您的代码没有处理异常,那么最终.NET Framework将处理它(即ASP.NET中的黄色死屏)。
您可以忽略第一次机会异常,因为它们适用于调试器。换句话说,您的异常代码(try-catch
逻辑)将不允许您与第一次机会异常进行交互。