gpt4 book ai didi

excel - 根据单元格值对行求和,然后删除所有重复项

转载 作者:行者123 更新时间:2023-12-03 20:23:13 25 4
gpt4 key购买 nike

我有一个 Excel 表,其中某些行可能包含与其他行相同的数据。我需要一个宏来对该列中的所有值求和并删除所有重复行,除了第一个行,它包含其余行的总和。
enter image description here
我已经尝试了多个版本的代码,产生最接近我需要的结果的代码看起来像这样,但是这段代码包含一个问题是:无限循环。

Sub delet()
Dim b As Integer
Dim y As Worksheet
Dim j As Double
Dim k As Double

Set y = ThisWorkbook.Worksheets("Sheet1")
b = y.Cells(Rows.Count, 2).End(xlUp).Row

For j = 1 To b
For k = j + 1 To b
If Cells(j, 2).Value = Cells(k, 2).Value Then
Cells(j, 3).Value = (Cells(j, 3).Value + Cells(k, 3).Value)
Rows(k).EntireRow.Delete
k = k - 1
ElseIf Cells(j, 2).Value <> Cells(k, 2).Value Then
k = k
End If
Next
Next
End Sub

最佳答案

我建议将数据放入数组中,然后进行相关操作。这是一个很小的范围,它可能不会影响性能,但对于更大的数据集,它会很重要。
这是你正在尝试的吗?

Option Explicit

Sub Sample()
Dim ws As Worksheet
Dim lRow As Long, i As Long, j As Long
Dim MyAr As Variant, outputAr As Variant
Dim col As New Collection
Dim itm As Variant
Dim totQty As Double

'~~> Change this to the relevant sheet
Set ws = Sheet1

With ws
'~~> Find last row of col A
lRow = .Range("A" & .Rows.Count).End(xlUp).Row

'~~> Get those value in an array
MyAr = .Range("A2:C" & lRow).Value2

'~~> Get unique collection of Fam.
For i = LBound(MyAr) To UBound(MyAr)
If Len(Trim(MyAr(i, 2))) <> 0 Then
On Error Resume Next
col.Add MyAr(i, 2), CStr(MyAr(i, 2))
On Error GoTo 0
End If
Next i

'~~> Prepare array for output
ReDim outputAr(1 To col.Count, 1 To 3)

i = 1

For Each itm In col
'~~> Get Product
For j = LBound(MyAr) To UBound(MyAr)
If MyAr(i, 2) = itm Then
outputAr(i, 1) = MyAr(i, 1)
Exit For
End If
Next j

'~~> Fam.
outputAr(i, 2) = itm

totQty = 0

'~~> Qty
For j = LBound(MyAr) To UBound(MyAr)
If MyAr(j, 2) = itm Then
totQty = totQty + Val(MyAr(j, 3))
End If
Next j

outputAr(i, 3) = totQty

i = i + 1
Next itm

'~~> Copy headers
.Range("A1:C1").Copy .Range("G1")
'~~> Write array to relevant range
.Range("G2").Resize(UBound(outputAr), 3).Value = outputAr
End With
End Sub
输出
enter image description here

关于excel - 根据单元格值对行求和,然后删除所有重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66693135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com