Option Explicit
Sub dowhileloop()
Dim x As Long
Dim sumX As Long
Dim ws As Worksheet
Dim n As Integer
Set ws = ThisWorkbook.Worksheets("test data")
For x = 2 To ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
sumX = ws.Cells(x, 5).Value2
n = 1
If ws.Cells(x, 2) = ws.Cells(x + n, 2) And ws.Cells(x, 4) = ws.Cells(x + n,
4) Then
sumX = sumX + ws.Cells(x + n, 5).Value
ws.Cells(x + n, 6) = sumX
Else
n = n + 1
End If
Next x
End Sub
我使用的逻辑不正确,无法获得我想要的输出。这是我第一次写VBA。
请建议。
答案 0 :(得分:0)
我可以看到的第一个问题是你没有将值重新放在工作表上,正如我在第一篇评论中提到的那样。
也许在你End If
后你需要类似的东西:
ws.Cells(x,2) = sumX
循环中的逻辑也是错误的。据我所知,这就是它正在做的事情:
循环1
x
= 2
sumX
= 78(单元格(2,5)=范围E2)
n
= 0
使用这些值您的IF条件是:
If cell B2 = cell B2 AND cell D2 = cell D2 then <this is always true>
sumX = 78 + 78
else
n = 1
end if
条件为真,那么n
没有增加,所以循环2说明:
sumX = 64
If cell B3 = cell B3 and cell D3 = cell D3 then <again true>
sumX = 64 + 64
else
n = n +1
end if
也许在循环之前使用n=1
?