提问人:vbanovice2222 提问时间:9/27/2023 更新时间:9/28/2023 访问量:33
Do While 循环 - 求和 - 粘贴仅部分工作
Do While Loop - Sum - Paste only partially working
问:
我正在尝试从数据集自动上传文件。根据客户的不同,我们将上传净额或总和数量。我想运行一个宏来执行以下操作:
- 检查客户端是粗的还是净的
- 如果为净值,则将此客户端下方所有行的数量相加(数据已排序)并粘贴到工作表 2 的相关列中 - 然后移动到下一行/客户端
- 如果粗略,则仅复制此行,粘贴到相关列中,然后移动到下一行
我的代码如下:
Sub netting()
Dim od As Worksheet
Dim eb As Worksheet
Dim mapping As Worksheet
Dim client As String
Dim currentvalue As Double
Dim row As Long
Dim i As Long
Dim p As Long
Set od = ThisWorkbook.Sheets("Original Data")
Set eb = ThisWorkbook.Sheets("EB Bulk Upload")
Set mapping = ThisWorkbook.Sheets("Mapping")
lastrow = od.Cells(od.Rows.Count, "H").End(xlUp).row
i = 20
p = 2
For i = 20 To lastrow
Dim clientid As String
clientid = od.Cells(i, "E").Value
Dim nettvalue As Variant
nettvalue = Application.WorksheetFunction.XLookup(clientid, mapping.Range("$B$2:$B$287" & lastRow), mapping.Range("$C$2:$C$287" & lastRow))
If nettvalue = "Y" Then
Dim sum As Double
sum = 0
Do While od.Cells(i, "E").Value = clientid
sum = sum + od.Cells(i, "H").Value
i = i + 1
Loop
eb.Cells(p, "F").Value = sumValue
ElseIf nettvalue = "N" Then
eb.Cells(p, "F").Value = od.Cells(i, "H").Value
End If
i = i + 1
p = p + 1
Next i
End Sub
现在实际发生的事情是:
- 第一个客户端数量已正确复制
- 第二个客户端跳过第 21 行,然后对以下行求和
- 然后,该宏在下一个客户端上不起作用。
下面是我想发生的事情的一个例子:
源数据
A列 | B列 |
---|---|
客户端 1 | -10 |
客户端 2 | 50 |
客户端 2 | -25 |
客户端 2 | 10 |
客户 3 | 10 |
客户 3 | 5 |
客户 4 | 100 |
成品数据:
A列 | B列 |
---|---|
客户端 1 | -10 |
客户端 2 | 35 |
客户 3 | 15 |
客户 4 | 100 |
答:
0赞
taller
9/27/2023
#1
您的代码具有嵌套循环(For+Do While),在修改迭代器时需要小心。外循环每次迭代都会将 i 递增 1(下一个 i)。当内部 Do 循环到达具有不同 clientId 的行时,它会中断。多行在嵌套循环中递增 i。这会导致通过跳转迭代跳过行。
更改两行
For i = 20 To lastrow
Dim clientid As String
clientid = od.Cells(i, "E").Value
Dim nettvalue As Variant
nettvalue = Application.WorksheetFunction.XLookup(clientid, mapping.Range("$B$2:$B$287" & lastRow), mapping.Range("$C$2:$C$287" & lastRow))
If nettvalue = "Y" Then
Dim sum As Double
sum = 0
Do While od.Cells(i, "E").Value = clientid
sum = sum + od.Cells(i, "H").Value
i = i + 1
Loop
eb.Cells(p, "F").Value = sumValue
i = i - 1 ' ** new code
ElseIf nettvalue = "N" Then
eb.Cells(p, "F").Value = od.Cells(i, "H").Value
End If
' i = i + 1 ** remove it
p = p + 1
Next i
评论