我正在运行一个数据导入宏,我想合并数据集中在 x 列中具有相等值的所有行,然后我想得到一个代表组 x[y] x 作为列的平均值的行,并且y 是该特定分组的 x 列的值。
是否有一个简单的功能可以做到这一点,或者我必须创建一个包含大量空闲周期的广泛循环?
显式: 所以我的数据集看起来像
A | B | C
1 2 4
1 2 5
2 7 3
2 5 1
3 2 1
1 5 6
现在我想按列 A 值合并行,因此所有具有相等值的 A 将其余行取平均值,因此我会得到如下所示的内容:
A | B | C
1 3 5
2 6 2
3 2 1
到目前为止,我一直在尝试通过此函数手动循环 A 列(1 到 10)的可能值,但它一直在崩溃 excel,我不知道为什么,我必须在某个地方有一个无限循环功能:
Function MergeRows(sheet, column, value)
Dim LastRow
Dim LastCol
Dim numRowsMerged
Dim totalValue
numRowsMerged = 1
LastRow = sheet.UsedRange.Rows.Count
LastCol = sheet.UsedRange.Columns.Count
With Application.WorksheetFunction
For iRow = LastRow - 1 To 1 Step -1
'enter loop if the cell value matches what we're trying to merge
Do While Cells(iRow, column) = value
For iCol = 1 To LastCol
'skip the column that we're going to use as merging value, and skip the column if it contains 3 (ikke relevant)
If Not (iCol = column) And Not (Cells(iRow, iCol) = 3) Then
Cells(iRow, iCol) = (Cells(iRow, iCol) * numRowsMerged + Cells(iRow + 1, iCol)) / (numRowsMerged + 1)
End If
Next iCol
'delete the row merged
Rows(iRow + 1).Delete
Loop
'add one to the total number of rows merged
numRowsMerged = numRowsMerged + 1
Next iRow
End With
End Function
解决方案 我最终创建了一个范围,我将使用 Union 逐渐扩展,如下所示:
Function GetRowRange(sheet, column, value) As range
Dim LastRow
Dim LastCol
Dim numRowsMerged
Dim totalValue
Dim rowRng As range
Dim tempRng As range
Dim sheetRange As range
numRowsMerged = 1
Set sheetRange = sheet.UsedRange
LastRow = sheet.UsedRange.Rows.Count
LastCol = sheet.UsedRange.Columns.Count
With Application.WorksheetFunction
For iRow = 1 To LastRow Step 1
'enter loop if the cell value matches what we're trying to merge
If (sheetRange.Cells(iRow, column) = value) Then
Set tempRng = range(sheetRange.Cells(iRow, 1), sheetRange.Cells(iRow, LastCol))
If (rowRng Is Nothing) Then
Set rowRng = tempRng
Else
Set rowRng = Union(rowRng, tempRng)
End If
End If
'add one to the total number of rows merged
numRowsMerged = numRowsMerged + 1
Next iRow
End With
Set GetRowRange = rowRng
End Function