2012-11-29 50 views
2

第一篇文章在這裏,所以我希望我很清楚。返回獨特的值,避免循環未過濾的範圍

我在工作表上有一個表,我正在使用。我已經將listObject傳遞給了一個類,它可以從中返回各種數據。我想通過篩選指定的列標題來檢索唯一列表。

我的問題是這樣的:

我可以返回一個包含所有行,一次過濾的範圍,而不需要通過整個手動循環,未經過濾的範圍是多少?

我目前的代碼循環遍歷(未過濾)範圍,尋找下面的唯一條目。它在我的測試工作表上花費了大量的時間,所以不要認爲它對於操作示例是可行的。

Public Function returnUniqueList(col As String) As Collection 
' get unqiue lists from the table. Useful for things like LCPs or ballast types 
' returns as list of strings 

Dim i As Integer 
Dim r As Excel.Range 
Dim reqCol As Integer 
Dim tempString As String 
' collection of strings with the unique values 
Dim retString As New Collection 

reqCol = returnColId(col) 

On Error GoTo errorCatch 

' collect the unique values 
For Each r In pLO.Range.rows 

    If Not InCollection(retString, r.Cells(1, reqCol)) Then 
     ' add to the collection, including the key 
     If r.Cells(1, reqCol) <> "" Then 
      retString.Add r.Cells(1, reqCol), r.Cells(1, reqCol) 
     End If 
    End If 
Next r 

Set returnUniqueList = retString 
Exit Function 
errorCatch: 
    MsgBox "Error returning unique list: " + Err.Description 

End Function 

回答

1

因此,在對各種內置的excel/VBA功能進行了一些調整之後,我已經選擇了高級過濾器。我遇到的一個問題是,當我在一列上過濾時,我想將過濾的表格返回到調用的一段代碼。上述函數現在看起來是這樣的:

Public Function returnUniqueList(col As String, searchTerm As String) As Excel.range 
' get unique lists from the table. Useful for things like LCPs or ballast types 
' returns as excel.range 

Dim reqCol As Integer 

On Error GoTo errorCatch 

reqCol = returnColId(col) 
Dim critRange As String 
Dim cr As Excel.range 


critRange = "=""=" + searchTerm + "*""" 

pWkSht.Cells(1, 1000) = col 
pWkSht.Cells(2, 1000) = critRange 

Set cr = pWkSht.range(pWkSht.Cells(1, 1000), pWkSht.Cells(2, 1000)) 
' filter for unique entries on this column 
pLO.range.Columns(reqCol).Select 
pLO.range.Columns(reqCol).AdvancedFilter Action:=xlFilterInPlace, Unique:=True, CriteriaRange:=cr 


Set returnUniqueList = pLO.range.SpecialCells(xlCellTypeVisible).EntireRow 
pWkSht.Cells(1, 1000) = Empty 
pWkSht.Cells(2, 1000) = Empty 
Exit Function 

errorCatch: 
MsgBox "Error returning unique list: " + Err.Description 

End Function 

,我發現了一件棘手的事情,然後在調用函數的範圍內工作。我發現excel範圍可以包含'區域'。這是由於excel與連續數據一起工作的原因。所以在調用函數中,我不得不遍歷返回範圍中的區域。這確實增加了我希望避免的原始調用函數的開銷水平(我想要返回一個單獨的範圍,並且可以輕鬆地遍歷一個單獨的區域)。

我發現通過從上面返回的範圍/區域迭代的最可靠的方法是基於這段代碼,我以一種或另一種方式在不同的地方使用不同的列(從列表中拉出不同的列等):

Set devices = edh.returnUniqueList("DaliCct", lcp) 
' filter by the requested LCP 

'clear down the dali ccts box 
daliCctsListBox.Clear 

' cycle through the returned areas, retrieving the relvant info 
For i = 1 To devices.Areas.Count 
    For rowInd = 1 To devices.Areas(i).rows.Count 
     Dim r As Excel.range 
     For Each r In devices.Areas(i).rows(rowInd) 

     If (r.Cells(daliCctColId) <> "") And (r.Cells(daliCctColId) <> "DaliCct") Then 
      daliCctsListBox.AddItem r.Cells(daliCctColId) 
      bAdded = True 
     End If 
     Next r 
    Next rowInd 
Next i