簡體   English   中英

檢查Excel工作表中是否存在單元格值,然后獲取底部單元格的值並將其添加

[英]Check if cell value exists in excel sheet, then get the values of the bottom cells and add it

我在工作表中有不同的定義類別(列A),這些類別分布在整個數據表中(F3:I14)。

我想為單元格F3:I14中的每個類別(a,b,c,d,e,f)添加值,該類別寫在其下方的已分配列(C列)中。

例如:對於類別a,添加來自單元格F3:I14的所有數字,該數字寫在單元格C2中a下方。

在此處輸入圖片說明

我嘗試了VLOOKUP公式,但是沒有用。

對於公式答案,請使用以下數組公式:

=SUM(IF($F$3:$I$14=A2,$F$4:$I$15))

作為數組公式,退出編輯模式時,需要使用Ctrl-Shift-Enter而不是Enter進行確認。 如果做得正確,那么excel會將{}放在公式周圍。

在此處輸入圖片說明

我支持Scott Craner的答案,因為我認為這是最好,最干凈的解決方案。 但是,當您用“ VBA”標記該問題時,我想我也將使用VBA為其提供純編程解決方案。 如果沒有其他說明,它說明了像Scott那樣的好公式多么簡單!

Sub SumCategories()
    Const startColumn As Integer = 6 'F
    Const endColumn As Integer = 9 'I
    Const startRow As Integer = 3
    Const endRow As Integer = 14

    Const categoryColumn As Integer = 1 'A
    Const assignedColumn As Integer = 3 'C
    Dim categoryRow As Integer
    categoryRow = 2

    Dim categoryTotalAssigned As Integer
    categoryTotalAssigned = 0

    Dim currentCategory As String
    currentCategory = ActiveSheet.Cells(categoryRow, categoryColumn)

    While Not currentCategory = ""
        'Loop through all data to sum totals
        For c = startColumn To endColumn
            For r = startRow To endRow Step 2 'Look in every other row
                If ActiveSheet.Cells(r, c) = currentCategory Then
                    categoryTotalAssigned = categoryTotalAssigned + ActiveSheet.Cells(r + 1, c)
                End If
            Next r
        Next c

        'Write total for category
        ActiveSheet.Cells(categoryRow, assignedColumn) = categoryTotalAssigned

        'Move to next row
        categoryRow = categoryRow + 1

        'Reset total for next category
        categoryTotalAssigned = 0

        'Get next category
        currentCategory = ActiveSheet.Cells(categoryRow, categoryColumn)
    Wend
End Sub

VBA腳本的結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM