如何获取特定单元格的值而不是整个范围

时间:2019-09-02 07:35:38

标签: excel vba

我有一个接受单元格范围的函数,但是我需要对其进行修改以接受某些单元格(不是A7:A14,而是A7,A9,A10,A11等)。我不知道我需要多少个单元格,因此它需要能够容纳未知数量的单元格。

以下是现有代码:

Function CountC(rng As Range, Cell As Range)
Dim CellC As Range, ucoll As New Collection
For Each CellC In rng
    If CellC.Interior.Color = Cell.Interior.Color And worksheetFunction.IsText(CellC) Then
        On Error Resume Next
           If Len(CellC) > 0 Then ucoll.Add CellC, CStr(CellC)
        On Error GoTo 0
    End If
Next CellC
CountC = ucoll.Count
End Function

2 个答案:

答案 0 :(得分:0)

ParamArray()是VBA中添加未指定数量的参数的方法。这是一个将所有内容串联在一起的示例:

Public Function CountMe(ParamArray myArray() As Variant) As String

    Dim myVar As Variant
    Dim result As String

    For Each myVar In myArray
        If IsObject(myVar) Then
            Dim myCell As Range
            For Each myCell In myVar
                result = result & " " & myCell
            Next
        Else
            result = result & " " & myVar
        End If
    Next
    CountMe = result

End Function

这应该是这样工作的:

enter image description here

答案 1 :(得分:0)

您可以将范围作为字符串移交给

Function CountC(rngString As String, Cell As Range)
Dim CellC As Range, ucoll As New Collection
Dim rng As Range
Set rng = Range(rngString)
For Each CellC In rng
    If CellC.Interior.Color = Cell.Interior.Color And WorksheetFunction.IsText(CellC) Then
        On Error Resume Next
        If Len(CellC) > 0 Then
            ucoll.Add CellC, CStr(CellC)
        End If
        On Error GoTo 0
    End If
Next CellC
CountC = ucoll.Count
End Function

例如使用

调用函数
=CountC("E1, E4, E8";D5)

也许不是最优雅的方式-但却可以