数据绑定组合框无法连接到指定的文件

时间:2013-06-27 01:12:54

标签: vb.net excel

我一直在研究下面的代码。我试图将组合框绑定到Sheet1列A6向下。我制定了以下代码,但是在找到声明的文件时遇到了问题。我检查了文件的名称,甚至复制和粘贴,但它仍然无法找到它。

 Imports System.Data
Imports System.Data.OleDb
Imports Microsoft.Office.Interop.Excel


Public Class dsbPositionBoard
    Private ConnectionNoHeader As String = "provider=Microsoft.Jet.OLEDB.4.0; data source='{0}';Extended Properties=""Excel 8.0;IMEX=1; HDR=No;"""

    Private Sub dsbPositionBoard_Startup() Handles Me.Startup

        Dim oExcel As New Microsoft.Office.Interop.Excel.Application
        Dim oBook As Microsoft.Office.Interop.Excel.Workbook
        Dim oSheet As Microsoft.Office.Interop.Excel.Worksheet

        oBook = oExcel.Workbooks.Open("2011.1004.Salary Survey Template.xlsm")
        oSheet = CType(oBook.Worksheets(1), Microsoft.Office.Interop.Excel.Worksheet)

        Using MyConnection As New System.Data.OleDb.OleDbConnection(String.Format(ConnectionNoHeader, oBook))
            MyConnection.Open()

            Dim da As New OleDbDataAdapter( _
            "SELECT DISTINCT * FROM [Sheet1$A1:A]", MyConnection)

            Dim dt As New System.Data.DataTable

            da.Fill(dt)

            cmbSelectPosition.DisplayMember = dt.Columns(0).ColumnName
            cmbSelectPosition.DataSource = dt
            'ediDate = dateComboBox.SelectedItem.ToString()


        End Using

    End Sub

1 个答案:

答案 0 :(得分:1)

您需要包含工作簿的完整路径:

oBook = oExcel.Workbooks.Open("H:\2011.1004.Salary Survey Template.xlsm") 

或更好(因为路径可以改变)你应该使用OpenFileDialog 来自:http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.aspx

    Dim openFileDialog1 As New OpenFileDialog()

    openFileDialog1.InitialDirectory = "c:\"
    openFileDialog1.Filter = "xlsm files (*.xlsm)|*.xlsm|All files (*.*)|*.*"
    openFileDialog1.FilterIndex = 2
    openFileDialog1.RestoreDirectory = True 

    If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then 
        oBook = oExcel.Workbooks.Open(openFileDialog1.filename) 
    Else
        Exit Sub
    End If