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

时间:2016-07-19 15:29:59

标签: excel vba excel-vba sorting

我试图在excel中创建一个vba函数,按单元格颜色对列进行排序,然后将结果输出到另一个位置。我所拥有的是目前给我一个错误

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

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

1 个答案:

答案 0 :(得分:1)

你需要使用类似的东西:

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

另外,您不需要Set cell = colorSearchRange,因为cell将在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