2012-07-19 200 views
-1

我有一張Excel工作表,其中創建了一個由多個值組成的列表。另外我創建了一個宏,它顯示了一個用戶窗體,其中這些值是硬編碼的。獲取單元格中的值列表

現在我希望窗體中的這些值自動/編程/動態添加到我的用戶窗體列表中,以便將來如果我想減少列表中的值,那麼我不必更改宏再次。

我一直在尋找答案,但我一直沒有找到我要找的東西。

我記錄了這個宏,但我不知道如何從中檢索值:

Sub Macro7() 
' 
' Macro7 Macro 
' 

' 
Range("E1").Select 
ActiveSheet.Range("$A$1:$AE$175").AutoFilter Field:=5 
End Sub 
+0

值填寫列表框一個窗體命名UReports這是列表中用戶窗體數組?或在一個組合框?或一個列表框?或者是其他東西? – 2012-07-19 16:28:14

+0

我想要在Excel單元格中獲取的值是以列表的形式。並啓用了過濾器。我想在用戶表單列表框中添加這些值。 – IConfused 2012-07-19 16:32:32

+0

在我給你的代碼之前,也許你想通過循環工作表中的列表來嘗試自己,然後使用'ListBox1.Add'來添加新項目? – 2012-07-19 16:39:56

回答

0

您指定將打開自動篩選你的活動工作表宏。這將提供列標題,允許用戶過濾到感興趣的內容。 假設這種工作表中篩選的是你想要的,你可以使用的東西,像什麼:

Dim r As Range 
'Note: set r to something useful, such as worksheet.Cells 

Dim vis As Range 
Set vis = r.SpecialCells(xlCellTypeVisible) 

'now vis holds a special "Range" object referring to the visible cells. 
'since (auto) filtering hides some cells, this vis range will help show only the cells that remain visible. 
'the output of SpecialCells, you should assume holds a complex Range, 
'which is composed of multiple Areas that are wrapped in one single Range object 
'the separate areas help you distinguish the visible cells from the hidden cells 
'fyi, various safety checks you can do: vis Is Range, vis Is Nothing 

Dim a as Areas 
Set a = r.Areas 

Dim cr as Range 
For Each cr in a 
    'cr refers to a single (i.e. normal and contiguous) area range 
    'where you can use cr.Row, cr.Column, cr.Rows.Count, cr.Columns.Count 
Next 

所以當你做過濾,可以使用SpecialCells(xlCellTypeVisible)揭示非隱藏的細胞,被表示爲具有包圍代表連續範圍的區域的範圍。

0

與具有一個名爲lbxReport列表框,這樣使用的代碼與來自E列

Sub ShowUf() 

    Dim ufReports As UReports 
    Dim rCell As Range 
    Dim colUnique As Collection 
    Dim i As Long 

    Set ufReports = New UReports 
    Set colUnique = New Collection 

    'loop through the cells in column E 
    For Each rCell In Sheet1.Range("E2", Sheet1.Cells(Sheet1.Rows.Count, 5).End(xlUp)).Cells 
     'Collections can't have duplicate keys, so we try to add all the values. If there 
     'are duplicates, the 'On Error' ignores them and we're left with a collection of 
     'only unique values from column E 
     On Error Resume Next 
      colUnique.Add rCell.Value, CStr(rCell.Value) 
     On Error GoTo 0 
    Next rCell 

    'loop through the collection and add them to the listbox 
    For i = 1 To colUnique.Count 
     ufReports.lbxReport.AddItem colUnique.Item(i) 
    Next i 

    'Show the form 
    ufReports.Show 

End Sub