VB.NET(Excel 两列 > 条件组合框)

VB.NET (Excel Two Columns > Conditional Comboboxes)

我搜索了将近两个小时以找到以下问题的解决方案。在 Excel 中,我有两列(一列用于主记录,一列用于从属记录)。基本上,在 Combobox1 中,我想填充所有主记录。如果选择了 MasterRecord A,我希望 Combobox2 只显示属于 A 的 SlaveRecords 而不是属于其他主记录的其他记录。

我添加了 Interop 程序集并 Excel 打开(已经有一个连接)。非常感谢您的帮助!

Private Sub Combobox2_Populate()
    'Start Excel Script to populate ComboBox2
    Dim excel As Application = New Application
    Dim w As Workbook = excel.Workbooks.Open(Filename:=databasestatus, [ReadOnly]:=True)
    Dim sheet As Worksheet = w.Sheets("AIR_NL_1")
    Dim StartRow As Integer
    Dim TotalRows As Integer
    ComboBox2.Items.Clear()
    sheet.UsedRange.AutoFilter(Field:=9, Criteria1:=ComboBox1.SelectedItem, Operator:=XlAutoFilterOperator.xlFilterValues)
    TotalRows = sheet.Range("A1").CurrentRegion.Rows.Count
    For StartRow = 3 To TotalRows
        If XlCellType.xlCellTypeVisible = True Then
            ComboBox2.Items.Add(sheet.Range("H:H").Cells(StartRow, 1).Text)
        End If
    Next
    w.Close(SaveChanges:=False)
End Sub    

这可能对你有帮助,或者至少给你一个基本的想法:

Private Function ExcelToDataTable(ByVal fileExcel As String, _ 
                                  Optional ByVal columnToExtract As String = "*", _
                                  ) As System.Data.DataTable
    Dim dt As New System.Data.DataTable
    Try
        Dim MyConnection As System.Data.OleDb.OleDbConnection
        Dim MyCommand As OleDbDataAdapter
        Dim fileExcelType As String

        'Chose the right provider
        If IO.Path.GetExtension(fileExcel.ToUpper) = ".XLS" Then
            fileExcelType = "Excel 8.0"
            MyConnection = _
            New System.Data.OleDb.OleDbConnection _
            ("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";")
        Else
            fileExcelType = "Excel 12.0"
            MyConnection = _ 
            New System.Data.OleDb.OleDbConnection _
            ("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & fileExcel & "';Extended Properties=" & fileExcelType & ";")
        End If

        'Open excel connection
        MyConnection.Open()

        'Populate DataTable
        Dim myTableName = MyConnection.GetSchema("Tables").Rows(0)("TABLE_NAME")
        MyCommand = New OleDbDataAdapter(String.Format("SELECT " & columnToExtract & " FROM [{0}] ", myTableName), MyConnection)
        MyCommand.TableMappings.Add("Table", columnToExtract)
        MyCommand.Fill(dt)
        MyConnection.Close()
    Catch ex As Exception
        Err.Clear()
    End Try
    Return dt
End Function

如您所见,我们有一个名为 myWhereStatement 的可选参数。

什么意思 您可以在调用函数时指定它的值,否则它的值将是一个 empty string

之后,我们可以在 Sub 中调用 ExcelToDataTable 来填充 ComboBox,如下所示:

Private Sub Combobox_Populate()
    Dim filePath As String = "your_file_path"
    ComboBox1.DataSource = ExcelToDataTable(filePath, "MasterRecord") 
End Sub

现在您的 ComboBox1 已填充数据,但 ComboBox2 仍然是空的。

我们将处理 ComboBox1_SelectedValueChanged 的事件,这意味着每次您 select 来自 ComboBox1 的项目时,它将以编程方式填充 ComboBox2正确的项目如下所示。

Private Sub ComboBox1_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedValueChanged
    Dim slaveRecords As System.Data.DataTable = ExcelToDataTable(filePath)
    Dim dt As New DataTable
    dt.Columns.Add("SlaveRecords")
    For i As Integer = 0 To slaveRecords.Rows.Count
        If ComboBox1.SelectedItem Is slaveRecords.Rows(i).Item(0) Then
            dt.Rows.Add(slaveRecords.Rows(i).Item(1))
        End If
    Next
    ComboBox2.DataSource = dt
End Sub

备注

如您所见,ExcelToDataTable 的第一个调用只有 2 个参数,而第二个调用有 3 个参数。这就是 optional parameter 功能!

N.B.

如您所见,我使用了很多 _ 因为更好的代码格式。这意味着单个 statement will continue across multiple lines

如果不是 100% 清楚您有任何疑问,请随时在下面的评论中提问。