【问题标题】:Populate .net combobox with used range from Excel sheet使用 Excel 工作表中的已用范围填充 .net 组合框
【发布时间】:2013-05-23 06:23:30
【问题描述】:

我正在尝试使用 Excel 工作簿中的已用范围填充 Windows 窗体上的组合框。我需要参考的 Excel 范围是 D32:D62;然而,这个范围是动态的。它可能只包含 5 个值,也可能包含 30 个,具体取决于用户在我的应用中输入的内容。此范围内的值将全部偏移到顶部,因此值之间不会有空白单元格。

      'populate ComboBoxProgram with relevant program names for loaded student
    Try

        Dim oRange As Excel.Range
        Dim oRangeArr As String

        oRange = DirectCast(StatVar.xlApp.Sheets("New Calculator Input").UsedRange("D32", "D62"), Excel.Range)
        oRangeArr = String.Empty
        'Build a string array delimited by commas
        For i As Integer = 1 To oRange.Rows.Count
            Dim oCell As Excel.Range = DirectCast(oRange.Rows(i), Excel.Range)
            oRangeArr &= DirectCast(oCell.Value.ToString, String) & ","
        Next

        oRangeArr = oRangeArr.Remove(oRangeArr.Length - 1, 1)
        ComboBoxProgram.Items.AddRange(oRangeArr.Split(","c))
        oRange = Nothing

    Catch exc As Exception
        MessageBox.Show("An error occured while retrieving the relevant programs from the budget. Please contact an administrator for assistance.")
    End Try

如果我范围内的所有单元格都有值,这只会填充我的组合框。如何找到已使用的范围?

【问题讨论】:

    标签: vb.net excel combobox


    【解决方案1】:

    试一试this 稍作修改的方法。它将检查整个工作簿中包含数据的单元格,而不是为空单元格填充组合框。

    Imports Microsoft.Office.Interop.Excel
    ...
    
    Dim excel As Application = New Application
    
    Dim w As Workbook = excel.Workbooks.Open("C:\temp\book1.xlsx")
        For i As Integer = 1 To w.Sheets.Count
              Dim sheet As Worksheet = w.Sheets(i)
              Dim r As Range = sheet.UsedRange
              Dim array(,) As Object = r.Value(XlRangeValueDataType.xlRangeValueDefault)
              If array IsNot Nothing Then
                  Dim bound0 As Integer = array.GetUpperBound(0)
                  Dim bound1 As Integer = array.GetUpperBound(1)
    
                  ' Loop over all elements.
                  For j As Integer = 1 To bound0
                      For x As Integer = 1 To bound1
                          Dim s1 As String = array(j, x)
                             If s1 IsNot Nothing Then
                                If Not ComboBox1.Items.Contains(s1.ToString) Then
                                    ComboBox1.Items.Add(s1.ToString)
                                End If
                             End If
                      Next
                  Next
              End If
         Next
     w.Close()
    

    【讨论】:

    • 如何防止重复我的组合框中的项目?现在它正在多次复制所有内容。我需要每个项目在我的工作表上只出现一次
    • 您可以在 add() 调用之前添加 ' If Not combobox1.items.contains(s1.tostring)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 2021-10-07
    • 1970-01-01
    • 2018-02-20
    • 2015-07-27
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多