计算VBA中不同单元的数量

我想要统计使用VBAselect不同的单元格。

考虑如果我们select五个不同的单元格 – D5,C2,E7,A4,B1。 有没有一种方法可以计算这些数量的细胞。

其次,我怎样才能检索这些单元格中的数据。 比方说,我想存储在一个数组中。

感谢您的帮助。

Dim rngCell as Range, arrArray() as Variant, i as integer Redim arrArray(1 to Selection.Cells.Count) i = 1 For each rngCell in Selection arrArray(i) = rngCell.Value i = i + 1 Next 

看起来你已经知道了,但是如果你想要的话,可以把它加载到一个数组中:

 Public Sub Example() Dim test() As Variant test = RangeToArray(Excel.Selection, True) MsgBox Join(test, vbNewLine) End Sub Public Function RangeToArray(ByVal rng As Excel.Range, Optional ByVal skipBlank As Boolean = False) As Variant() Dim rtnVal() As Variant Dim i As Long, cll As Excel.Range ReDim rtnVal(rng.Cells.Count - 1) If skipBlank Then For Each cll In rng.Cells If LenB(cll.Value) Then rtnVal(i) = cll.Value i = i + 1 End If Next ReDim Preserve rtnVal(i - 1) Else For Each cll In rng.Cells rtnVal(i) = cll.Value i = i + 1 Next End If RangeToArray = rtnVal End Function 

谢天谢地,我通过这样做了一个办法 – Selection.Cells.Count

它返回给我所选单元的单元数。

但我仍然坚持dynamic分配这个值到一个数组,如—

I = Selection.Cells.Count Dim ValArr(I)