【问题标题】:Excel VBA Exporting 2 Column Listbox to Separate WorksheetExcel VBA 将 2 列列表框导出到单独的工作表
【发布时间】:2016-03-01 00:09:29
【问题描述】:

我正在尝试将 2 列列表框导出到新工作表。我想在新工作表中显示每一列。这需要重复两次,因为有 3 个列表框。用户将在列表框中选择所需的行,然后按下单独的“确认”命令按钮。

我编写了以下代码,它将仅导出每个列表框的第一列。我使用 RowSource 使列表框变成双列。

非常感谢任何帮助。

 Private Sub ConfirmBtn_Click()
 Dim emptyRow As Long

   Sheet2.Activate

   emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

   Cells(emptyRow, 1).Value = SRCLstBox.Value
   Cells(emptyRow, 3).Value = BERLstBox.Value
   Cells(emptyRow, 5).Value = SNKLstBox.Value
End Sub

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    您可以像这样使用List 属性:

    With SRCLstBox
        Cells(emptyRow, 1).Value = .Value
        Cells(emptyRow, 2).Value = .List(.ListIndex, 1)
    End With
    With BERLstBox
        Cells(emptyRow, 3).Value = .Value
        Cells(emptyRow, 4).Value = .List(.ListIndex, 1)
    End With
    With SNKLstBox
        Cells(emptyRow, 5).Value = .Value
        Cells(emptyRow, 6).Value = .List(.ListIndex, 1)
    End With
    

    【讨论】:

      【解决方案2】:

      ListBoxValue 属性只会为您提供所选 项的第一列的内容。如果列表中没有任何项目被选中,那么您将获得NULL 作为返回值。

      要从ListBox 获取所有项目,您需要使用List( , ) 方法。下面是一个小样本 Sub 给你的想法:

      Public Sub WriteAndReadFromListBox()
      
      Dim lngRow As Long
      
      ' Adding 21 rows of 'hello world' in two columns
      Load UserForm1
      For lngRow = 0 To 20
          UserForm1.ListBox1.AddItem
          UserForm1.ListBox1.List(lngRow, 0) = "hello"
          UserForm1.ListBox1.List(lngRow, 1) = "world"
      Next lngRow
      
      ' Selecting the first row allows you to use the
      ' .Value property and get 'hello' (from the first column)
      UserForm1.ListBox1.Selected(0) = True
      Debug.Print UserForm1.ListBox1.Value
      
      ' The following lines of code will write the entire content
      ' of the ListBox to the sheet with the Index 1
      For lngRow = 0 To UserForm1.ListBox1.ListCount
          Sheets(1).Cells(lngRow + 1, 1).Value2 = UserForm1.ListBox1.List(lngRow, 0)
          Sheets(1).Cells(lngRow + 1, 2).Value2 = UserForm1.ListBox1.List(lngRow, 1)
      Next lngRow
      
      UserForm1.Show
      
      End Sub
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-12
        • 1970-01-01
        相关资源
        最近更新 更多