在vba中使用vlookup对多个列求和

时间:2016-05-30 14:17:19

标签: excel vba excel-vba vlookup

我试图在vba中使用vlookup对多个列进行求和。我可以用这种方式将其作为Excel公式

{=SUM(VLOOKUP(LookupValue,LookupRange,{FirstColumnNo,2ndColumnNo,...,LastColumnNo},0))}

在VBA中,我似乎没有运气,因为我也在使用这个公式的For循环。你可以总结很多这些查找,但我正在寻找更短更优雅的东西

我当前的代码

For i = 1 To ProdCurrentQtr
''''''''Gross Values
ThisWorkbook.Sheets("Central").Cells(i + 8, 1) = ThisWorkbook.Sheets("Central").Cells(i + 8, 2) & "_" & ThisWorkbook.Sheets("Central").Cells(i + 8, 3)
ThisWorkbook.Sheets("Central").Cells(i + 8, 5) = Application.VLookup(ThisWorkbook.Sheets("Central").Cells(i + 8, 1), LookupRangeCentral, 6, 0) _
+ Application.VLookup(ThisWorkbook.Sheets("Central").Cells(i + 8, 1), LookupRangeCentral, 7, 0) _
+ Application.VLookup(ThisWorkbook.Sheets("Central").Cells(i + 8, 1), LookupRangeCentral, 8, 0) _
+ Application.VLookup(ThisWorkbook.Sheets("Central").Cells(i + 8, 1), LookupRangeCentral, 9, 0) _
+ Application.VLookup(ThisWorkbook.Sheets("Central").Cells(i + 8, 1), LookupRangeCentral, 10, 0) _
+ Application.VLookup(ThisWorkbook.Sheets("Central").Cells(i + 8, 1), LookupRangeCentral, 12, 0)
Next i

但我正在寻找的东西是

ThisWorkbook.Sheets("Central").Cells(i + 8, 5).FormulaArray = Application.Sum(Application.VLookup(ThisWorkbook.Sheets("Central").Cells(i + 8, 1), LookupRangeCentral, [6,7,8,9,10,12], 0)) 

任何帮助表示赞赏

2 个答案:

答案 0 :(得分:0)

    With ThisWorkbook.Sheets("Central").Cells(8,1)
       For i = 1 To ProdCurrentQtr
         .Offset(i) = .Offset(i, 1) & "_" & .Offset(i, 2)
          Set found = LookupRangeCentral.Find(What:=.Offset(i), LookAt:=xlWhole, LookIn:=xlValues)
          If Not found Is Nothing Then .Offset(I, 4) = Application.WorksheetFunction.Sum(found.Offset(,5).Resize(,7)) - found.Offset(,10)
       Next i
    End With 

数组公式方法如下

   With ThisWorkbook.Sheets("Central").Cells(9,1)
       .Resize(ProdCurrentQtr).FormulaR1C1 = "=RC[1] & "" _ "" & RC[2]"
       .Offset(,4).FormulaArray = "=SUM(VLOOKUP(" & .Address(False, False) & "," & LookupRangeCentral.Address(,,,True) & ",{6,7,8,9,10,12},0))"
       .Offset(,4).AutoFill Destination:=.Offset(,4).Resize(ProdCurrentQtr)
   End With 

答案 1 :(得分:0)

以下公式可以满足您的需求。只是一个选项:

=SUMPRODUCT(INDEX((ISNUMBER(MATCH(A11:A16,A2:A6&"_"&B2:B6,0)))*(ISNUMBER(SEARCH("," & COLUMN(B11:G16)& ",",",2,4,6,7,")))*B11:G16,))

",2,4,6,7,"是实际的列号,而不是相对的。

这是对上述列中的值进行求和,其中的名称在A2中找到:A6&“_”& B2:B6。

enter image description here