[英]Sum multiple columns using vlookup in vba
我正在嘗試在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))
任何幫助表示贊賞
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.