我想要计算使用VBA选择的不同单元格。
考虑我们是否选择了五个不同的细胞--D5,C2,E7,A4,B1。 有没有办法计算这些细胞数量。
其次,我如何检索这些单元格中的数据。假设我想将它存储在一个数组中。
感谢您的帮助。
答案 0 :(得分:3)
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
答案 1 :(得分:1)
看起来你已经弄明白了,但是如果你需要的话可以将它加载到数组中:
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
答案 2 :(得分:0)
谢天谢地,我做了一个方法 - Selection.Cells.Count
它返回所选单元格的单元格数。
但我仍然坚持动态地将这个值分配给数组,如---
I = Selection.Cells.Count Dim ValArr(I)