2012-05-11 32 views
0

我总是收到类型不匹配错误或除以零错误,尝试执行以下操作:我只想计算一个范围内唯一条目的数量,范围内的条目是“类“文本:范围内唯一条目的数量,VBA

startRow = 3 
startColumn = 1 
col = "A" 
Set topCell = Cells(startRow, startColumn) 
Set bottomCell = Cells(Rows.Count, startColumn) 
If IsEmpty(bottomCell) Then Set bottomCell = bottomCell.End(xlUp) 
Set selectRows = Range(col & topCell.Row & ":" & col & bottomCell.Row) 
nRows = WorksheetFunction.CountA(selectRows) 

test = WorksheetFunction.SumProduct(WorksheetFunction.IsText(selectRows)/WorksheetFunction.CountIf(selectRows, selectRows)) 

我有一个测试计算错误,但我不明白。一些帮助非常赞赏

非常感谢

BR 马丁

+0

虽然'IsText'将在一个工作表函数'Range'对象,我不认为它会接受一个'Range'在VBA中?我一直在玩弄它,并且无法获得VBA中工作表函数的相同行为 – psubsee2003

回答

0

你的第一个问题是你test计算WorksheetFunction.CountIf(selectRows, selectRows)一部分。当没有重复时,这将导致除以零错误。在输入工作表时也会发生这种情况,所以您需要更改逻辑或首先测试这种情况。

您的Type Mismatch问题我相信是由WorksheetFunction.IsText(selectRows)段造成的。我一直无法弄清楚是什么导致了它,但正如我在我的评论中提到的那样,我认为IsText()函数可能不像VBA中输入一个单元格时那样使用范围。

我可能会以不同的方式来解决这个问题。下面是我在其他地方找到的一个例子。SO Count unique values in Excel 这大部分都有工作表公式,但有一个VBA代码的答案可能会适应。

另一种选择是创建一个收集和计算元素的数量

Sub CountUnique() 
Dim Col As New Collection 
Dim i As Integer 

On Error Resume Next 

For i = 3 To 10 
    Col.Add Sheet1.Cells(i, 1).Value, Sheet1.Cells(i, 1).Value 
Next 

MsgBox Col.Count 

On Error GoTo 0 
End Sub