将组合框添加到选定的文件Visual Studio 2010 VB

时间:2014-01-28 17:49:59

标签: visual-studio-2010 excel vba combobox

我想使用VS2010创建一个.exe文件来选择excel文件,并通过组合框读取它的页面。

我现在已经排序以制作一个'浏览'按钮来选择excel文件并生成一个msgbox但是却无法指定组合框来读取它的页面。

这是我的代码

导入Microsoft.Office.Interop 导入Microsoft.Office.Interop.Excel

Public Class 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

结束班

提前致谢!

1 个答案:

答案 0 :(得分: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()不正确