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

时间:2018-09-17 11:26:54

标签: excel vb.net combobox conditional

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

enter image description here

我添加了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    

1 个答案:

答案 0 :(得分:0)

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

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中选择一个项目时,它将以编程方式用适当的项目填充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%清楚的事情,您可以在下面的评论中随意提出疑问。