2014-01-28 113 views
-1

我想使用VS2010製作一個.exe文件來選擇excel文件,並通過組合框讀取它的工作表。將組合框添加到選定的文件Visual Studio 2010 VB

我現在已經整理了一個'瀏覽'按鈕來選擇excel文件並生成一個msgbox,但是卻不能指定組合框來讀取它的工作表。

這裏是我的代碼

進口Microsoft.Office.Interop 進口的Microsoft.Office.Interop.Excel

公共類Form1中

Public Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click 
    Dim myFileDlog As New OpenFileDialog() 
    'Dim oXL As Excel.Application 
    'Dim oWB As Excel.Workbook 
    'Dim oSheet As Excel.Worksheet 


    'look for files in the c drive 
    myFileDlog.InitialDirectory = "c:\" 

    'specifies what type of data files to look for 
    myFileDlog.Filter = "All Files (*.*)|*.*" & _ 
     "|Data Files (*.xls)|*.xls" & _ 
     "|Data Files (*.xlsx*)|*.xlsx*" & _ 
     "|Data Files (*.xlsm*)|*.xlsm*" 

    'specifies which data type is focused on start up 
    myFileDlog.FilterIndex = 2 

    'Gets or sets a value indicating whether the dialog box restores the current directory before closing. 
    myFileDlog.RestoreDirectory = True 

    'seperates message outputs for files found or not found 
    If myFileDlog.ShowDialog() = _ 
     DialogResult.OK Then 
     If Dir(myFileDlog.FileName) <> "" Then 
      MsgBox("File Exists: " & _ 
        myFileDlog.FileName, _ 
        MsgBoxStyle.Information) 
     Else 
      MsgBox("File Not Found", _ 
        MsgBoxStyle.Critical) 
     End If 
    End If 

    'Adds the file directory to the text box 
    txtFileDirectory.Text = myFileDlog.FileName 
End Sub 

Public Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged 
    'Dim oXL As Excel.Application 
    Dim oWB As Excel.Workbook 
    Dim oSheet As Excel.Worksheet 
    'Dim oRng As Excel.Range 

    For x As Integer = 1 To FileDialog.Sheets.Count() 
     If TypeOf oWB.Sheets(x) Is Excel.Worksheet Then 
      ComboBox1.Items.Add(FileDialog.Sheets(x).name) 
     End If 
    Next 
    ComboBox1.SelectedIndex = 0 
End Sub 

末級

在此先感謝!

回答

0

您需要先設置工作簿oWB,然後使用下面的內容。

變化

If TypeOf oWB.Sheets(x) Is Excel.Worksheet Then 
     ComboBox1.Items.Add(FileDialog.Sheets(x).name) 
    End If 

If TypeOf oWB.Sheets(x) Is Excel.Worksheet Then 
     ComboBox1.Items.Add(oWB.Sheets(x).name) 
    End If 

同樣FileDialog.Sheets.Count()

不正確
相關問題