如何将选定的范围复制到给定的数组?

我有145个类别的重复列表,每个类别有15列数据。 我通过将类别数量减less到24个并添加相应的数据来巩固这个列表。

例如,如果最初我有ABCDEFG分类,并且我合并了,我将所有的值添加到A中,比如F,来获得一个新的分类。

另一个问题是所有这145个类别在60多个时间段内重复。 所以我必须分别合并每个时间段的数据。

要做到这一点,我正在尝试使用数组。

Sub CategoriesToSectors() Dim k As Integer Dim j As Integer Dim p As Integer Dim Destination As Range ' p is just a filler/dummy variable until I later decide which categories go into which sector Dim CategoryData(144, 14) As Long Dim SectorData(23, 14) As Long k = 0 ' k should go Upto 60 ' I first copy the data from a range in the first worksheet into the array CategoryData ' Then I move 145 rows down for the next time-period's data and repeat this whole process While k < 60 Sheets("ReformattedData").Select Range("B1:P145").Select ActiveCell.CurrentRegion.Offset(k * 145, 0).Select CategoryData = Selection.Value For j = 0 To 14 SectorData(0, j) = CategoryData(1, j) + CategoryData(6, j) + CategoryData(8, j) + CategoryData(13, j) For p = 1 To 23 SectorData(p, j) = CategoryData(15, j) + CategoryData(19, j) + CategoryData(31, j) + CategoryData(44, j) Next p Next j ' paste consolidated sectordata array one below another in SectorData worksheet Sheets("SectorData").Select Range("B2").Select Set Destination = ActiveCell.Offset(k * 25, 0) Destination.Resize(UBound(SectorData, 1), UBound(SectorData, 2)).Value = SectorData Wend End Sub 

正如你所看到的,我正在做的是首先尝试将第一个范围块复制到CategoryData数组中。 然后,我将数据合并到扇区数组中 – 我刚刚使用了重复的值来testing它 – 带p的for循环不应该存在。 我最终将使用24个不同的语句来创buildSectorData数组。

然后,我将合并的数据粘贴到另一张纸上。 我回到第一张纸上,向下移动下一个范围块的select(第一个单元格下面的145个单元格),然后select这个数据并重复。

这似乎不工作 – 错误的数据input到第一个数组 – CategoryData。

帮助将不胜感激。

谢谢

为了将Range复制到VBA数组中,您必须使用Variant:

 Dim CategoryData() As Variant 'or just CategoryData As Variant (no brackets) 'then the following will work CategoryData = Selection.Value 

一旦你传输了数据,你可以检查UBound的CategoryData。

在cpearson这里有一个有用的讨论。

只要尺寸相同,您可以将Range设置为一个数组(在您的示例中为SectorData),而不是Variant。

尝试这个:

 Sub RangeToArray() Dim NewArray As Variant Dim SourceRange As Range Set SourceRange = Selection.CurrentRegion NewArray = SourceRange.Value Stop 'to check the result in Immediate Window End Sub