Excel VBA函数给出了奇怪的回报

我的情况如下:

我有一个function:

Function test(TestValue As String, TargetRange As Range) As String Dim rng2 As String Dim C As Range For Each C In TargetRange If C.Text = TestValue Then If rng2 <> vbNullString Then rng2 = rng2 & "," & C.Address Else rng2 = C.Address End If End If Next test = rng2 End Function 

这个查找具有特定值的单元格的范围,并将单元格地址添加到string中。 这工作得很好。

第二我有function2号:

 Function CountCellsByColor2(rData As String, cellRefColor As Range) As Long Dim indRefColor As Long Dim cellCurrent As Range Dim cntRes As Long Dim test As Long 'Application.Volatile cntRes = 0 indRefColor = cellRefColor.Cells(1, 1).Interior.Color For Each cellCurrent In Range(rData) If indRefColor = cellCurrent.Interior.Color Then cntRes = cntRes + 1 End If Next cellCurrent CountCellsByColor2 = cntRes End Function 

这一个使用带有地址的string,并检查给定颜色的单元格,并返回多less个单元格具有给定颜色的数字。

到目前为止非常简单。

现在我的问题,当我的string不超过20单元格地址一切工作完美,但是当我添加到31左右颜色函数返回#值!

当我使用它从另一张表让我们说=CountCellsByColor2(test("Apple";!SomeSheetF2:F300);H5)例如。 我得到一些没有input或正确的答案或#Value!

所以,如果我跳出一些excel或Vba的限制,我并不是真的。 或者,也许我的一连串细胞变得很大。 我希望有人快速看到出了什么问题。

我相信你在联盟运营商(逗号)遇到了一个限制。 Union方法本身具有30个参数的限制,所以,使用你的string创build方法,在31处返回一个错误是有道理的。

编辑:看来这不是应用的联盟限制。 而问题是Range对象的参数的长度。 当我testing时,我没有看到错误,直到我有大约40个单元的论点。 进一步的经验testing表明,当Range对象的参数大于255个字符时,会产生一个错误。 此限制也可能适用于其他VBA对象或语句或方法的参数。

要对现有代码进行最小限度的更改,请尝试以下操作,它将分隔逗号分隔的范围列表并逐个testing它们。

这是为了帮助您了解您的编码问题。 但是,可能有更有效的方法来编码你想要做的事情。


 Function CountCellsByColor2(rData As String, cellRefColor As Range) As Long Dim indRefColor As Long Dim cellCurrent As Variant Dim cntRes As Long Dim test As Long 'Application.Volatile cntRes = 0 indRefColor = cellRefColor.Cells(1, 1).Interior.Color For Each cellCurrent In Split(rData, ",") If indRefColor = Range(cellCurrent).Interior.Color Then cntRes = cntRes + 1 End If Next cellCurrent CountCellsByColor2 = cntRes End Function 

使第一个参数是一个string

在这里输入图像说明

你为什么使用string来收集单元格? 一个集合使得它更容易。

 Function Test(TestValue As String, TargetRange As Range) As Collection Dim c As Range 'Initialize collection Set Test = New Collection 'Loop through range For Each c In TargetRange If (c.Text = TestValue) Then Test.Add c End If Next c End Function Function CountCellsByColor2(rData As Collection, cellRefColor As Range) As Long Dim indRefColor As Long Dim cellCurrent As Range 'Determine color indRefColor = cellRefColor.Cells(1, 1).Interior.Color 'Loop through all cells For Each cellCurrent In rData If (cellCurrent.Interior.Color = indRefColor) Then CountCellsByColor2 = CountCellsByColor2 + 1 End If Next cellCurrent End Function