按颜色sorting并输出到另一个位置

我试图在Excel中创build一个vba函数,通过单元格颜色对列进行sorting,然后将结果输出到另一个位置。 我有什么是目前给我一个错误

Function SortColor(colorSearchRange As Range, colorToSearch As Range, outputRange As Range) Dim colorValue As Integer Dim coloredItems(150) As String Dim index As Integer colorValue = colorToSearch.Interior.ColorIndex index = 0 Set cell = colorSearchRange For Each cell In colorSearchRange If cell.Interior.ColorIndex = colorValue Then coloredItems(index) = cell.Value index = index + 1 End If Next cell Range(outputRange & UBound(coloredItems) + 1) = WorksheetFunction.Transpose(coloredItems) End Function 

我是新的视觉基础。 任何types的帮助将不胜感激。

你需要使用像这样的东西:

 outputRange.Resize(index) = WorksheetFunction.Transpose(coloredItems) 

另外,您不需要Set cell = colorSearchRange ,因为cell将在For Each cell In colorSearchRange每次迭代中设置For Each cell In colorSearchRange循环中

终于你的Function没有返回任何东西,所以你可以使它成为一个Sub

以上所有内容都可能导致以下内容:

 Sub SortColor(colorSearchRange As Range, colorToSearch As Range, outputRange As Range) Dim colorValue As Long, index As Long Dim coloredItems() As String Dim cell As Range ReDim coloredItems(1 To colorSearchRange.Rows.Count) As String 'dim your array to the maxiumum possible for the passed range colorValue = colorToSearch.Interior.ColorIndex For Each cell In colorSearchRange If cell.Interior.ColorIndex = colorValue Then index = index + 1 coloredItems(index) = cell.Value End If Next cell outputRange.Resize(index) = WorksheetFunction.Transpose(coloredItems) End Sub