我正在运行dataimport宏,并且想要合并数据集中列x中具有相同值的所有行,然后我希望获得一行代表组x [y] x的平均值是列,y是该特定分组的列x的值。excel以编程方式合并列z中具有相同值的所有行
是否有一个简单的功能来做到这一点,还是我必须创建一个大量的备用循环的广泛循环?
明晰化: 所以我的数据集看起来像
A | B | C
1 2 4
1 2 5
2 7 3
2 5 1
3 2 1
1 5 6
现在我要合并的列列的值,因此,所有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
解决方案 我结束了创建,我将逐步推广使用联盟的范围,就像这样:
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
你找谁最终 - >'组别1 | Group1,Group2 |的平均值Group2,Group3 |的平均值平均Group3'? – 2013-02-14 14:51:00
你可以进入更多的细节?不知道我明白你想要做什么... – 2013-02-14 16:29:21
请明确说明downvote,否则我不知道如何不再犯这个错误 – Jakob 2013-02-15 17:21:11