【问题标题】:VB.NET (Excel Two Columns > Conditional Comboboxes)VB.NET(Excel 两列 > 条件组合框)
【发布时间】:2019-02-21 07:33:55
【问题描述】:

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

我添加了互操作程序集并打开了 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    

【问题讨论】:

  • 您能否向我们提供一个complete and verifiable 示例,说明您迄今为止所做的尝试?提前致谢!
  • 西莫你好。请在上面找到。所以我已经用 A 列(或 I 列)(主记录)中的记录填充了 Combobox1。我尝试使用 Combobox1.SelectedItem 捕获主记录选择。我现在尝试的是过滤工作表,然后尝试用所有从属记录填充 B 列(或 H 列)。
  • 我建议您使用以下逻辑:使用返回所有主记录的查询填充 DataTable。使用返回属于 MasterRecords 的 SlaveRecords 的查询填充第二个 DataTable。用第一个数据表填充ComboBox1,用第二个数据表填充ComboBox2。 @YassinKulk 你明白了吗?
  • 现在我要发射了,大约一年半后我会回来。如果您仍然为此苦苦挣扎,我会做出适当的回答。
  • 嗨西莫。享用午餐!我明白你提出的逻辑。作为 vb.net 的新手,我将尝试找到有关创建此数据表的示例。谢谢!

标签: excel vb.net combobox conditional


【解决方案1】:

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

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 的事件,这意味着每次您从ComboBox1 中选择一个项目时,它都会以编程方式使用如下所示的propper 项目填充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 功能!

注意

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

如果有些事情不是 100% 清楚,或者您有任何疑问,请随时在下面的 cmets 中提问。

【讨论】:

  • 西莫你好。绝对精彩。谢谢一个不。我将把它注入我的脚本并从那里开始,但基本原理对我来说都很清楚。祝你一切顺利!
  • 是的,认为您的 excel 是一个 sql 表并按照此操作。是否可以在 where 子句中使用某种元素来匹配从属记录与主记录?如果不告诉我,我会找到解决方案。
  • 嗨 Simo,我在上面添加了一张图片。非常感谢您在这里支持我的奉献精神,真的很感激。
  • @YassinKulk 不确定它是否有效,请尝试输入 group by MasterRecords 而不是 your_where_clauses...
  • @YassinKulk 至少你试过了,我很确定这不起作用,所以我没有浪费时间,我研究了另一个解决方案。我正在编辑答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-29
  • 1970-01-01
相关资源
最近更新 更多