[Visual Basic] 纯文本查看 复制代码Sub combineExpenses()
Dim currentRow As Long
Dim currentFamily As String
Dim currentName As String
Dim currentType As String
Dim currentAge As String
Dim currentExpense As Double
Dim leaderRow As Long
Dim leaderExpense As Double
' Start from row 2 (assuming row 1 is the header row)
currentRow = 2
' Loop through all rows until an empty cell is encountered in the "家庭" column
Do Until Cells(currentRow, 1).Value = ""
' Get the values of the current row
currentFamily = Cells(currentRow, 1).Value
currentName = Cells(currentRow, 2).Value
currentType = Cells(currentRow, 3).Value
currentAge = Cells(currentRow, 4).Value
currentExpense = Cells(currentRow, 5).Value
' Check if the current row is a child
If currentAge = "孩子" Then
' Find the row of the leader in the same family
leaderRow = findLeader(currentFamily)
' If a leader is found, add the child's expense to the leader's expense
If leaderRow > 0 Then
leaderExpense = Cells(leaderRow, 5).Value
Cells(leaderRow, 5).Value = leaderExpense + currentExpense
Cells(currentRow, 5).Value = 0
End If
End If
' Move to the next row
currentRow = currentRow + 1
Loop
End Sub
Function findLeader(family As String) As Long
Dim currentRow As Long
Dim currentFamily As String
Dim currentType As String
' Start from row 2 (assuming row 1 is the header row)
currentRow = 2
' Loop through all rows until an empty cell is encountered in the "家庭" column
Do Until Cells(currentRow, 1).Value = ""
' Get the values of the current row
currentFamily = Cells(currentRow, 1).Value
currentType = Cells(currentRow, 3).Value
' If the current row is a leader in the same family, return the row number
If currentFamily = family And currentType = "领导者" Then
findLeader = currentRow
Exit Function
End If
' Move to the next row
currentRow = currentRow + 1
Loop
' If no leader is found, return 0
findLeader = 0
End Function
试运行后能够把demo前面的变成第二个表格