Connectionstring属性尚未初始化vb.net

我认为解决办法是宣布他已经做了cnnExcel,但我不能得到错误的乘法。 错误行是

cnnExcel.Open() 

这里是代码

 Public Class Form1 Dim cnnExcel As New OleDbConnection Public Function GetExcelSheetNames() As String() Dim conStr As String = "" Dim dt As DataTable = Nothing Dim opExcel As New OpenFileDialog opExcel.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls" opExcel.ShowDialog() Dim pathExcel As String = opExcel.FileName If pathExcel.Trim = "" Then MessageBox.Show("Please select file !") Return Nothing Else Dim Ext As String = pathExcel.Substring(pathExcel.LastIndexOf(",") + 1) If Ext.Length = 3 Then conStr = "Provider=Microsoft.jet.OLEDB.4.0;Data Source=" + pathExcel + ";Extended Properties='Excel 8.0;HDR=yes;IMEX=1';" ElseIf Ext.Length = 4 Then conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathExcel + ";Extended Properties='Excel 12.0 xml;HDR=Yes';" End If cnnExcel = New OleDbConnection(conStr) cnnExcel.Open() dt = cnnExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing) If dt Is Nothing Then Return Nothing End If Dim excelSheetNames As [String]() = New [String](dt.Rows.Count - 1) {} Dim i As Integer = 0 For Each row As DataRow In dt.Rows excelSheetNames(i) = row("TABLE_NAME").ToString() i += 1 Next cnnExcel.Close() Return excelSheetNames End If End Function 

由于您正在初始化If...ElseIf的连接string,但它仍然未初始化,这意味着两个条件都不匹配,所以Ext.Length既不是= 3也不是= 4 。 原因是您正在使用pathExcel.LastIndexOf(",")而不是pathExcel.LastIndexOf(".")

但是,我会使用System.IO.Path.GetExtension

 Dim extension = System.IO.Path.GetExtension(pathExcel) If extension.Equals(".xls", StringComparison.InvariantCultureIgnoreCase) Then conStr = "Provider=Microsoft.jet.OLEDB.4.0;Data Source=" + pathExcel + ";Extended Properties='Excel 8.0;HDR=yes;IMEX=1';" ElseIf extension.Equals(".xlsx", StringComparison.InvariantCultureIgnoreCase) Then conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathExcel + ";Extended Properties='Excel 12.0 xml;HDR=Yes';" Else ' should not happen with the current OpenFileDialog settings ' Throw New NotSupportedException("Illegal file-path, it must be either .xls or .xlsx") End If