我有一个文本框,我可以输入任何金额,例如3,000.00,然后是一个看起来像
的数据网格视图Category | Amount
Supmat | 2,000
POL | 500
Others | 400
POL | 500
获取我使用此代码的总数
For i As Integer = 0 To DataGridView1.RowCount - 1
If DataGridView1.Rows(i).Cells("Category").Value = "Supplies/Materials" Then
supmat += DataGridView1.Rows(i).Cells("Amount").Value
ElseIf DataGridView1.Rows(i).Cells("Category").Value = "Legal Expenses" Then
legal += DataGridView1.Rows(i).Cells("Amount").Value
ElseIf DataGridView1.Rows(i).Cells("Category").Value = "POL" Then
pol += DataGridView1.Rows(i).Cells("Amount").Value
ElseIf DataGridView1.Rows(i).Cells("Category").Value = "Others" Then
oth += DataGridView1.Rows(i).Cells("Amount").Value
End If
If CDec(txtFund.Text) > supmat Then
supmat1 = supmat
remain = CDec(txtFund.Text) - supmat
If legal > 0 Then
If remain > legal Then
legal1 = legal
remain2 = remain - legal
If pol > 0 Then
If remain2 > pol Then
pol1 = pol
remain3 = remain2 - pol
If oth > 0 Then
If remain3 > oth Then
oth1 = oth
Else
oth1 = remain3
End If
Else
oth1 = remain3
End If
Else
pol1 = remain2
oth1 = 0
End If
ElseIf oth > 0 Then
If remain2 > oth Then
oth1 = oth
Else
oth1 = remain2
End If
End If
Else
legal1 = remain
pol1 = 0
oth1 = 0
End If
ElseIf pol > 0 Then
If remain > pol Then
pol1 = pol
remain2 = remain - pol
If oth > 0 Then
If remain2 > oth Then
oth1 = oth
Else
oth1 = remain2
End If
Else
oth1 = remain2
End If
Else
pol1 = remain
oth1 = 0
End If
ElseIf oth > 0 Then
If remain > oth Then
oth1 = oth
Else
oth1 = remain
End If
End If
Else
supmat1 = CDec(txtFund.Text)
legal1 = 0
pol1 = 0
oth1 = 0
End If
Next
我得到总数为3000的输出
Supmat = 2000
Legal = 0
POL = 1000
Others = 0
但我需要的输出是
Supmat = 2000
Legal = 0
POL = 600
Others = 400
如果你检查我的类别,我首先输入Supmat 2000然后输入POL 500,然后输入其他400,最后再输入POL 500。我只需要得到总数3000但是因为最后一个POL是500,我应该只得到100。因为我已经拥有前三个中的2000 + 500 + 400。
有人可以帮助我在我的datagridview中输入的代码,而不是获取每个类别的总数。
我附上了一张关于我想要输出的示例图片 上面的代码可以做输出
Supmat = 2000
Legal = 0
POL = 1000
Others = 0
答案 0 :(得分:0)
试试这个......循环通过您的数据将总值和每个小计值传递给calcTotal
,它处理实际计算并更新总计。当总值<= 0时,退出循环。
Private Sub MainCalculation()
Dim supmat As Decimal = 0
Dim legal As Decimal = 0
Dim pol As Decimal = 0
Dim oth As Decimal = 0
Dim total_value As Decimal = CDec(Me.txtFund.Text)
For i As Integer = 0 To DataGridView1.RowCount - 1
Dim t As Decimal = DataGridView1.Rows(i).Cells("Amount").Value
Select Case DataGridView1.Rows(i).Cells("Category").Value
Case "Supplies/Materials"
calcTotal(supmat, total_value, t)
Case "Legal Expenses"
calcTotal(legal, total_value, t)
Case "POL"
calcTotal(pol, total_value, t)
Case "Others"
calcTotal(oth, total_value, t)
End Select
If total_value <= 0 Then Exit For
Next
Debug.Print("Supmat = " & supmat)
Debug.Print("Legal = " & legal)
Debug.Print("POL = " & pol)
Debug.Print("Others = " & oth)
End Sub
Private Sub calcTotal(ByRef subtotal As Decimal, ByRef total_value As Decimal, t As Decimal)
If total_value > t Then
subtotal += t
total_value -= t
Else
subtotal += total_value
total_value = 0
End If
End Sub