如何计算非矩形范围的列中的单元格

所以我有一个范围,将由用户select。 这将是两列,通常不相邻。 我需要计算所选范围每列中单元格的数量,以确定每列中单元格的数量是否相等。 (如果不是,我需要调整范围。)

例如,用户可以selectB5:B10和D6:D9。 所以我需要代码分别返回6和4。

我试过了:

Set rng = Selection rng.Columns(1).Count 

这返回1,这显然不是我需要的数字。

提前致谢!

您可以使用Range对象的Areas方法来获取Range的区域。 区域是在非连续范围内的连续范围的组。

 Set rng = Selection For i = 1 to rng.Areas.Count debug.print rng.Areas(i).Cells.Count Next 

这里有一个警告,你可能需要testing,那就是如果用户select,例如A1:B10,只需拖动鼠标。 由于这是一个连续的范围,它将只有一个Area ,你不会得到两个不同的数字。 如果你需要testing这个,你可以做如下的事情。

 Set rng = Selection 'non-contiguous ranges will always return one column, if there are mutiple columns both cell counts are equal by default If rng.Columns.Count = 1 Then For i = 1 to rng.Areas.Count debug.print rng.Areas(i).Cells.Count Next End If 

该死的@斯科特 – 只是打败了我。

尽pipe我正在使用Rows属性 – 如果用户selectA1:B19 ,它将在数组的单个元素中返回19,如果他们selectA1:A19 ,然后B1:B19 ,它将在数组的两个元素中返回19。
使用Cells ,它将在单个元素中返回38,或者在两个元素中返回19。

 Sub Test() Dim rRange As Range Dim lRows() As Long Dim x As Long Set rRange = Selection With rRange ReDim lRows(1 To .Areas.Count) For x = 1 To .Areas.Count lRows(x) = .Areas(x).Rows.Count Next x End With End Sub