我正在编写一个excel vba子例程,它总结了客户每年购买的lbs,但由于某种原因,子例程失败了。它打印出B
列中的所有客户名称,但是对于2011年,它会打印该行中的所有0
,并打印2012年,2013年和2014年0
位于第一列,就是这样。
Private Sub lbsPerCustPerYear_Click()
Dim i As Integer
Dim Cust As Range
Dim Cust2 As Range
Dim Total2011 As Long
Dim Total2012 As Long
Dim Total2013 As Long
Dim Total2014 As Long
Dim Output As Range
Dim OutputY2011 As Range
Dim OutputY2012 As Range
Dim OutputY2013 As Range
Dim OutputY2014 As Range
Dim CustLbs As Range
Dim Cust2Lbs As Range
Dim YearD As Range
Total = 0
Set Cust = Range("C6")
Set Cust2 = Range("C7")
Set CustLbs = Range("Q6")
Set Cust2Lbs = Range("Q7")
Set Output = Sheets("Sheet10").Cells(2, 2)
Set OutputY2011 = Sheets("Sheet10").Cells(2, 3)
Set OutputY2012 = Sheets("Sheet10").Cells(2, 4)
Set OutputY2013 = Sheets("Sheet10").Cells(2, 5)
Set OutputY2014 = Sheets("Sheet10").Cells(2, 6)
Set YearD = Range("K6")
For i = 0 To 14750
If IsDate(Sheets("Sheet1").Cells(6 + i, 11)) And IsNumeric(Sheets("Sheet1").Cells(6 + i, 17)) Then
If Year(YearD) = "2011" Then
Total2011 = Total2011 + CustLbs.Value
Output.Value = Cust.Value
OutputY2011.Value = Total
ElseIf Year(YearD) = "2012" Then
Total2012 = Total2012 + CustLbs.Value
Output.Value = Cust.Value
OutputY2012.Value = Total
ElseIf Year(YearD) = "2013" Then
Total2013 = Total2013 + CustLbs.Value
Output.Value = Cust.Value
OutputY2013.Value = Total
ElseIf Year(YearD) = "2014" Then
Total2014 = Total2014 + CustLbs.Value
Output.Value = Cust.Value
OutputY2014.Value = Total
End If
If Cust.Value = Cust2.Value Then
Set Cust = Cust.Offset(1, 0)
Set Cust2 = Cust2.Offset(1, 0)
Set CustLbs = CustLbs.Offset(1, 0)
Set Cust2Lbs = Cust2Lbs.Offset(1, 0)
Set YearD = YearD.Offset(1, 0)
Else
Set Cust = Cust.Offset(1, 0)
Set Cust2 = Cust2.Offset(1, 0)
Set CustLbs = CustLbs.Offset(1, 0)
Set Cust2Lbs = Cust2Lbs.Offset(1, 0)
Set Output = Output.Offset(1, 0)
Set OutputY2011 = OutputY2011.Offset(1, 0)
Set OutputY2012 = OutputY2011.Offset(1, 0)
Set OutputY2013 = OutputY2011.Offset(1, 0)
Set OutputY2014 = OutputY2011.Offset(1, 0)
Set YearD = YearD.Offset(1, 0)
Total2011 = 0
Total2012 = 0
Total2013 = 0
Total2014 = 0
End If
Else
Set Cust = Cust.Offset(1, 0)
Set Cust2 = Cust2.Offset(1, 0)
Set CustLbs = CustLbs.Offset(1, 0)
Set Cust2Lbs = Cust2Lbs.Offset(1, 0)
Set YearD = YearD.Offset(1, 0)
End If
Next i
End Sub
对于为什么会发生这种情况的任何帮助都将不胜感激。
答案 0 :(得分:0)
我首先使用MsgBox来验证每次迭代的变量。您可以通过这种方式查明问题。
MsgBox(Cust&“”& Cust2&“”& Total2011)
答案 1 :(得分:0)
您定义Total = 0
但在此之前永远不会更改它:OutputY2011.Value = Total
您的代码似乎每年使用不同的总变量(即Total2011
):尝试更改输出(最后一行是我更改过的):
For i = 0 To 14750
If IsDate(Sheets("Sheet1").Cells(6 + i, 11)) And IsNumeric(Sheets("Sheet1").Cells(6 + i, 17)) Then
If Year(YearD) = "2011" Then
Total2011 = Total2011 + CustLbs.Value
Output.Value = Cust.Value
OutputY2011.Value = Total2011