VBA阵列等于Range

时间:2014-02-06 15:10:57

标签: arrays excel vba excel-vba

关于VBA的简短问题。我有这段代码

Dim colEmployees As New Collection
Dim recEmployee As New clsEmployee
Dim LastRow As Integer, myCount As Integer
Dim EmpArray As Variant

LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row
EmpArray = ActiveSheet.Range(Cells(1, 1), Cells(LastRow, 4))

并在电子表格中显示... enter image description here

现在我已经做了很多阅读以掌握阵列是如何工作的,我已经看过像

这样的exaples
Dim myArray As Variant
Dim myArray (1 to 10, 1 to 20)
myArray = Array(“Name”, “Address”, “Phone”, “Email”)

我完全理解它们,但是当你有一个类似于此的数组时

EmpArray = ActiveSheet.Range(Cells(1, 1), Cells(LastRow, 4))

如何将数据实际保存在EmpArray等一维数组中?您是否需要一个维度用于行,一个用于列?我的意思是阵列将如何实际存储数据 - 按什么顺序(“Tracy”,“Bill”,“1651”,“1509”,......)或(“Tracy”,“1651”,“25”, “45”)?通常在阵列中存储范围,特别是一维的范围对我来说看起来很奇怪。我的3本VBA书籍都没有深入探讨这一点......

如果它是一个二维数组,代码如何继续如下:

Sub EmpPayCollection()
Dim colEmployees As New Collection
Dim recEmployee As New clsEmployee
Dim LastRow As Integer, myCount As Integer
Dim EmpArray As Variant

LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row
EmpArray = ActiveSheet.Range(Cells(1, 1), Cells(LastRow, 4))

For myCount = 1 To **UBound(EmpArray)**
Set recEmployee = New clsEmployee
With recEmployee
.EmpName = EmpArray(myCount, 1)
.EmpID = EmpArray(myCount, 2)
.EmpRate = EmpArray(myCount, 3)
.EmpWeeklyHrs = EmpArray(myCount, 4)
colEmployees.Add recEmployee, .EmpID
End With
Next myCount
MsgBox “Number of Employees: “ & colEmployees.Count & Chr(10) & _
“Employee(2) Name: “ & colEmployees(2).EmpName
MsgBox “Tracy’s Weekly Pay: $” & colEmployees(“1651”).EmpWeeklyPay
Set recEmployee = Nothing
End Sub

如果没有明确说明拾取的尺寸,它如何使用UBound?我知道这是可选的...但是你能否考虑到你的答案......?

1 个答案:

答案 0 :(得分:2)

它不会将数据存储为单个维度的数组,而是将其存储为基于2维1的数组。范围的值属性(包含多个单元格)返回一个二维数组(此处隐含值,因为它是范围的默认属性)。在您的示例中,数组看起来像:

Tracy   1651    25  45
Bill    1509    25  50

第一个维度指定行,第二个维度指定列 - 就像单元格对象一样。

这会回答你的问题吗?