总和使用指数vba excel

有人可以告诉我正确的语法,我试图执行此代码? 从string值的一维范围,我想select一个特定的string说“this”,并计算所有显示在下一列的“this”的值的总和。 它一直在吃我的头几个小时。 还有,还有更好的办法吗?

With Application.WorksheetFunction Range("AA2").Value = .Sum(.Index(ws(1).Range("F8"), .Match(ws(1).Range("AA1"), ws(1).Range("E8:E16"), 0), 0) **:** .index(ws(1).Range("F16"), .Match(ws(1).Range("AA1"), ws(1).Range("E8:E16"), 0), 0) End With 

在Excel中它将是:

 =SUMIF(E8:E16,"=this",F8:F16) 

所以在你的macros中尝试一下:

 Option Explicit Public Sub StackOverflowDemo() Dim conditionText As String Dim ws As Worksheet Dim target As Range Dim sourceCriteria As Range Dim sourceSum As Range Set ws = ThisWorkbook.Sheets(1) conditionText = "this" Set target = ws.Range("AA2") Set sourceCriteria = ws.Range("E8:E16") 'the above stuff would probably be passed as parameters since I doubt you want that stuff hard coded 'from here on there's no hard coding. Set sourceSum = sourceCriteria.Offset(0, 1) target.Value = WorksheetFunction.SumIf(sourceCriteria, "=" & conditionText, sourceSum) End Sub 

更新:重构显示使用variables的重用性/好处:

 Option Explicit Public Sub StackOverflowDemo() Dim ws As Worksheet Set ws = ThisWorkbook.Sheets(1) DoSumIf ws.Range("E8:E16"), "this", ws.Range("AA2") DoSumIf ws.Range("E8:E16"), "that", ws.Range("AA3") DoSumIf ws.Range("B2:B32"), "who", ws.Range("AA4") End Sub Private Sub DoSumIf(sourceCriteria As Range, conditionText As String, target As Range) Dim sourceSum As Range Set sourceSum = sourceCriteria.Offset(0, 1) target.Value = WorksheetFunction.SumIf(sourceCriteria, "=" & conditionText, sourceSum) End Sub 

你可以在VBA中使用这个function:这将在E2:E300中searchstring“P09”,然后直接向右求和列。

 Sub Test123455() Dim MyRange As Range Set MyRange = Nothing Dim curcell As Range For Each curcell In Range("E2:E300") If InStr(1, curcell.Value, "P09", vbTextCompare) > 0 Then If MyRange Is Nothing Then Set MyRange = curcell Else Set MyRange = Union(MyRange, curcell.Offset(0, 1)) End If End If Next curcell MsgBox Application.WorksheetFunction.Sum(MyRange) End Sub