假设我有下表:
https://i.imgur.com/qa2kiFv.png
在另一张表中,我有一列,其中包含以逗号分隔的扣减编号值,例如:(例如1、4、6)。
如何查找所有对应的扣除数点值并将它们相加?
例如,如果该单元格表示7、1、2a,则其总和为-15,-5和-2,总计为-22。
示例:https://i.imgur.com/CjhNkZU.png
(注意:我没有足够的声誉来发布图片,因此,如果有人愿意像编辑帖子一样添加图片并添加图片,我将不胜感激。)
答案 0 :(得分:1)
要执行此操作,必须将数据转换为Excel结构化表格(备份工作簿,选择数据,然后按“ Ctrl” +“ T”,为表格指定名称)
检查以获取更多参考:
https://support.office.com/en-us/article/overview-of-excel-tables-7ab0bb7d-3a9e-4b56-a3c9-6c94334e492c
本质上,您应该有两个表,如下所示: -包含扣除点的表格(我称之为TableDeduction) -包含典型扣除号的表(我称之为TableTypical)
将此代码复制并粘贴到模块中,并自定义下面的每一行>>>>自定义:
Sub GetPoints()
' Declare objects variables
Dim typicalTable As ListObject
Dim deductionTable As ListObject
Dim typicalCell As Range
' Declare other variables
Dim sheetName As String
Dim typicalTableName As String
Dim deductionTableName As String
Dim typicalValues As Variant ' Array
Dim deductionValue As Integer ' Change for long if sum is gonna be greater than 32.000
' Generic variables
Dim counter As Integer
' >>>> Customize to fit your needs
sheetName = "Sheet1"
typicalTableName = "TableTypical"
deductionTableName = "TableDeduction"
' <<<<
' Initiate table objects
Set typicalTable = ThisWorkbook.Worksheets(sheetName).ListObjects(typicalTableName)
Set deductionTable = ThisWorkbook.Worksheets(sheetName).ListObjects(deductionTableName)
' Loop through the typical table cells
For Each typicalCell In typicalTable.DataBodyRange.Columns(1).Cells
' Validate that it's valid
If typicalCell.Value <> "None" Then
' Reinitiate the sum
deductionValue = 0
' Split to cell values by commas
typicalValues = Split(typicalCell.Value, ",")
' For each value look it's corresponding deduction points
For counter = 0 To UBound(typicalValues)
' >>>> Customize the columns number
If IsError(Application.Match(CStr(typicalValues(counter)), deductionTable.DataBodyRange.Columns(1), 0)) Then
' >>>> Customize the columns number
' Lookup the table for numbers
If IsNumeric(Application.Index(deductionTable.DataBodyRange.Columns(2), Application.Match(CLng(typicalValues(counter)), deductionTable.DataBodyRange.Columns(1), 0))) Then
' >>>> Customize the columns number
deductionValue = deductionValue + Application.Index(deductionTable.DataBodyRange.Columns(2), Application.Match(CLng(typicalValues(counter)), deductionTable.DataBodyRange.Columns(1), 0))
End If
Else
' >>>> Customize the columns number
' Lookup the table for string
If IsNumeric(Application.Index(deductionTable.DataBodyRange.Columns(2), Application.Match(CStr(typicalValues(counter)), deductionTable.DataBodyRange.Columns(1), 0))) Then
' >>>> Customize the columns number
deductionValue = deductionValue + Application.Index(deductionTable.DataBodyRange.Columns(2), Application.Match(CStr(typicalValues(counter)), deductionTable.DataBodyRange.Columns(1), 0))
End If
End If
' Output the value in the next cell
typicalCell.Offset(0, 1).Value = deductionValue
Next counter
End If
Next typicalCell
End Sub