循环使用VBA Excel中特定列的已用范围

时间:2016-01-04 09:15:52

标签: excel vba excel-vba

我想获取特定列中所有单元格的值,并将它们添加到列表中 这是我试过的

Dim rng As Range
'here ColumnName will be like "A", "B" etc...
'and SheetName will be like "Sheet001", "Sheett002" etc...
rng = ThisWorkbook.Sheets(SheetName).Columns(ColumnName).UsedRange
For Each cell In rng.Cells
If Not cell.Value = "" Then
ListBox1.AddItem (cell.Value)
End If
Next

但是我无法确定如何通过名称来获取列的使用范围。 我想要阅读的数据将在单独的表中

enter image description here

1 个答案:

答案 0 :(得分:3)

UsedRange将引用已使用的工作表范围。使用UsedRange,您可以选择所需的列。

我稍微修改了你的代码。见下文:

Sub SomeSub()
    Dim MySht As Worksheet
    Dim MyRng As Range

    Set MySht = ThisWorkbook.Sheets("Sheet1")
    Set MyRng = MySht.UsedRange.Columns("A")

    For Each cell In MyRng.Cells

        If Not cell = "" Then
          'If your List Box is in "Sheet1"
          Sheets("Sheet1").ListBox1.AddItem (cell)
          'If your List Box is in "UserForm1"
          UserForm1.ListBox1.AddItem (cell)
        End If
    Next

    'To clear ListBox1 data
'    Sheets("Sheet1").ListBox1.Clear
'    UserForm1.ListBox1.Clear

End Sub