我试图解析连续范围的数据(orng),并从orng创建子范围,这些子范围在orng的第6列中包含相同的字符串值。每个子范围有1-15行和38列。据我所知,我无法为每个子范围创建一个新的范围对象,因为子范围的数量是未知的。我创建了一个数组,其中包含子范围(aData)的数据。我已经将其与下面的代码一起使用,但是我觉得有一种更简洁的方法无法确定。我也尝试过使用字典,但没有成功。我最终将不得不调用所有数据进行计算,并且使用多个嵌套的for循环访问每个元素似乎很麻烦。
我正在使用Excel Professional Plus 2016(不确定是否重要)。
使用数组是我可以设法获得所需最终结果的唯一方法,这很好。我希望数组是动态的,但是每当我尝试ReDim Preserve方法时,值都不会保存到数组中。数组的大小将是完美的,但是每个元素都是“空”。根据{{3}},“数组的每个元素必须分别分配其值”,所以我想我不能以块的形式将范围值分配给数组。找到网页后,我实现了一个具有预定结构和嵌套for循环的数组。
理想情况下,我可以将组织划分为不同的区域,但是由于它是连续的,所以我无法这样做。我想知道的是1)是否有更好的方法来做我想做的事情? (更易于阅读,更快,更少的代码,等等。2)如果没有更好的方法,是否可以就如何使此代码更简洁(动态范围,更少的循环,更好的结构)获得一些建议?
Private Sub rangetest()
Dim twb As Workbook: Set twb = ThisWorkbook
Dim cws As Worksheet: Set cws = twb.Sheets("Cleaned_2019+")
Dim orng As Range
Dim datelot As String, datelotcomp As String
Dim c As Long, i As Long, j As Long, k As Long, numrows As Long, lastrow
As Long, numlots As Long, _
curRow As Long, lotRows As Long, startRow As Long, layerRows As Long,
aRow As Long
Dim aLot() As Variant, aData(9, 49, 37) As Variant
Dim Z As Boolean
Set orng = cws.Range("A973:AL1014") 'Set initial range to work with.
numrows = orng.Rows.Count 'Number of rows in orng.
curRow = 1 'Current row in orng.
startRow = 1 'Starting row in orng for next
layer (changes when lot changes).
i = 0 'Layer of array (for aLot and aData arrays).
j = 0 'Row in orng where values for previous layer ended.
Z = False
Do Until Z = True
datelot = Left(orng.Cells(curRow, 6).Value, 10) 'Lot that we want the data for. Corresponds to a layer in the aData array.
datelotcomp = Left(orng.Cells(curRow + 1, 6).Value, 10) 'Lot of the next row in data sheet.
If datelot <> datelotcomp Then 'If datelotcomp <> to datelot then we want a new layer for array.
layerRows = curRow - j 'Number of rows for a particular layer
ReDim Preserve aLot(i) 'Array of lot names
aLot(i) = datelot 'Assign lot name to aLot array
For aRow = 1 To layerRows 'Row index in array
For lotRows = startRow To curRow 'Loops through orng rows and sets those values in array
For c = 1 To 38 'Loops through columns. There are always 38 columns
aData(i, aRow - 1, c - 1) = orng.Cells(lotRows, c).Value 'Add values to each index in array
Next c
Next lotRows
Next aRow
j = curRow
i = i + 1
startRow = curRow + 1
End If
If curRow = numrows Then 'End loop at end of orng
Z = True
End If
curRow = curRow + 1
Loop
numlots = i
End Sub
我得到的结果是一个数组,结构为aData(9,49,37),其中包含前4层aData(1-3,,)中的数据。这与orng中的手数相对应,因此代码可以正常工作。我只想咨询我是否效率低下。
我将再次检查以回答问题或进行澄清。
编辑1:
最终有兴趣的人对此问题进行了Microsoft(代码审查)的回答。