列出组合框中所有打开的Excel工作表

时间:2016-04-23 08:21:13

标签: vb.net excel

我想要一个组合框,列出目前在Excel中打开的所有工作表名称。

我找到了一些代码,列出了所有打开的工作簿,并编辑了这些代码来完成工作表。它似乎正确地在所有工作簿中正确循环,但它只列出当前活动的excel工作簿上的工作表。

下面的当前代码。在加载表单时调用此子句。

    dt.Columns.Add("sheets")
    Try
        If IsNothing(app) Then
            app = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
        End If
        Dim bks = app.Workbooks
        Dim dks = app.Worksheets
        dt.Clear()
        For Each bk As Excel.Workbook In bks
            Debug.WriteLine(bk.Name)
            For Each dk As Excel.Worksheet In dks
                Debug.WriteLine(dk.Name)
                dt.Rows.Add(dk.Name.ToString())
            Next
        Next
        ComboBox1.DataSource = Nothing
        ComboBox1.Items.Clear()
        ComboBox1.DataSource = dt
        ComboBox1.DisplayMember = "sheets"
    Catch ex As Exception
        MsgBox(ex.ToString())
    End Try

2 个答案:

答案 0 :(得分:0)

您正在循环之前阅读此内容:

Dim dks = app.Worksheets

Application.Worksheets返回有效工作簿的工作表。

使用两个嵌套循环时,如果不使用外循环变量,则必须出错。
试试这样:

    Dim bks = app.Workbooks
    'Dim dks = app.Worksheets
    dt.Clear()
    For Each bk As Excel.Workbook In bks
        For Each ws As Excel.Worksheet In bk.Worksheets
            dt.Rows.Add(bk.Name & ":" & ws.Name)
        Next
    Next

答案 1 :(得分:0)

我刚刚测试了下面的脚本,它似乎工作正常。试一试,看看你的想法。

Imports System.Data.OleDb

Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim filePath As String = "C:\Users\xxx\YourFile.xlsm"

        Dim connString As String = String.Empty
        If filePath.EndsWith(".xlsx") Then            '2007 Format            
            connString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=No'", filePath)
        Else            '2003 Format            
            connString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=No'", filePath)
        End If         'Get the Sheets in Excel WorkBook        
        Dim connExcel As New OleDbConnection(connString)
        Dim cmdExcel As New OleDbCommand()
        Dim oda As New OleDbDataAdapter()
        cmdExcel.Connection = connExcel
        connExcel.Open()
        ComboBox1.DataSource = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
        ComboBox1.DisplayMember = "TABLE_NAME"
        ComboBox1.ValueMember = "TABLE_NAME"
        connExcel.Close()
    End Sub

End Class