2013-06-27 69 views
0

我一直在研究下面的代碼一段時間了。我正試圖將組合框綁定到Sheet1列A6。我制定了以下代碼,但它在查找已聲明的文件時遇到了問題。我檢查了文件的名稱,甚至複製並粘貼,但仍無法找到它。數據綁定combobox無法連接到指定的文件

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 
+0

哪裏錯誤?是oBook線上的錯誤? – Kasnady

+0

對不起。是的,錯誤發生在oBook = oExcel.Workbooks.Open(「2011.1004.Salary Survey Template.xlsm」)上。該文件不在C:\,但在我的可移動。如果這有所作爲。 –

+0

其實,你的文件名實際上是錯誤的,我認爲你必須改變。和另外一個。先嚐試一下,「。」是關於格式的短語 – Kasnady

回答

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