Excel vb 在 a 列中查找定义的文本,找到的每个位置都采用下一行中的数值,并添加到所有此类名称的总计中。
例如,在 A 列的 4 个不同行(查看整个行范围)中,找到“产品 A”。 B 列右侧是不同的时间。我希望它根据名称“产品 A”将所有小时数相加,对于其他名称也是如此。
Sub SumHoursByProduct() 昏暗的工作表 将 ProductDict 变暗为对象 调暗最后一行只要 暗淡我只要 将产品名称变暗为字符串 昏暗的时间双倍
' Set the worksheet where data is located
Set ws = ThisWorkbook.Sheets("Sheet1") ' Change "Sheet1" to your sheet name if necessary
' Create a dictionary to hold product names and total hours
Set productDict = CreateObject("Scripting.Dictionary")
' Find the last row in column A
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
' Loop through each row in column A
For i = 1 To lastRow ' Start from row 1 to the last row
productName = ws.Cells(i, 1).Value ' Get product name from column A
hours = ws.Cells(i, 2).Value ' Get hours from column B
' Check if the product name is already in the dictionary
If productDict.exists(productName) Then
' Add the hours to the existing product name's total
productDict(productName) = productDict(productName) + hours
Else
' If product name not in dictionary, add it and set initial hours
productDict.Add productName, hours
End If
Next i
' Output the results
Dim outputRow As Long
outputRow = 1 ' Start output from row 1 (or change as needed)
ws.Cells(outputRow, 4).Value = "Product Name" ' Header for product names
ws.Cells(outputRow, 5).Value = "Total Hours" ' Header for total hours
outputRow = outputRow + 1 ' Move to the next row for output
' Write results to columns D and E
Dim key As Variant
For Each key In productDict.Keys
ws.Cells(outputRow, 4).Value = key ' Write product name in column D
ws.Cells(outputRow, 5).Value = productDict(key) ' Write total hours in column E
outputRow = outputRow + 1 ' Move to the next row for output
Next key
MsgBox "Total hours calculated for each product and outputted in columns D and E.", vbInformation
结束子