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

时间:2013-08-01 17:23:21

标签: arrays excel vba

我有145个类别的重复列表,每个类别有15列数据。 我正在通过将类别数量减少到24并添加相应数据来合并此列表。

例如, 如果最初我有类别A B C D E F G并且我合并了,我会在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数组中。然后,我将数据组合到扇区数组中 - 我刚刚使用重复值来测试它 - 带p的for循环不应该存在。我最终将使用24个不同的语句来创建SectorData数组。

然后我将Consolidated数据粘贴到另一张纸上。我回到第一张纸并向下移动我的选择以获得下一个范围块(第一个单元格下方的145个单元格)然后我选择这些数据并重复。

这似乎不起作用 - 将数据输入第一个数组时出错 - CategoryData。

帮助将不胜感激。

谢谢

2 个答案:

答案 0 :(得分:6)

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

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

转移数据后,您可以检查UBound的CategoryData。

这里有一个有用的讨论at cpearson

只要尺寸相同,您就可以将范围设置为数组(示例中为SectorData),而不是Variant。

答案 1 :(得分:0)

试试这个:

productFlavors {
    appFlavorA{
        applicationId "de.test.appaA"
    }
    appFlavorB{
        applicationId "de.test.appaB"
    }
}