2014-02-24 44 views
0

我有一個子我寫了一個SUMIFS語句包含在它。當yearRange與gEvent值匹配並且yearRange.Offset(0,2)匹配gEvent.Offset(0,2)時,我希望總和某個列(yearRange.Offset(0,i + 3))。我試着用google搜索這個問題,並檢查了MSDN網站(這不是很具描述性),並且無法讓這個功能正常工作。我唯一可能的想法是我使用的標準是字符串而不是整數。所以gEvent.Value可能是「ABCD」,而gEvent.Offset(0,2)可能是「DEFG」。在多個字符串標準的VBA SUMIFS

當我嘗試運行它的代碼是打破這裏:

itemPY = Application.WorksheetFunction.SumIfs(yearRange.Offset(0, i + 3), yearRange.Value, "=" & gEvent.Value & """, yearRange.Offset(0, 2), " = " & gEvent.Offset(0, 2).Value & """) 

而且我收到的錯誤是: 運行時錯誤「424」: 所需的對象

這裏是其完整的形式:

Sub CombineData() 

Dim eventSheet As Worksheet 
Dim yearSheet As Worksheet 
Dim yearRange As Range 
Dim eventRange As Range 
Dim gYear As Range 
Dim gEvent As Range 
Dim i As Integer 
Dim itemCount As Integer 
Dim itemPY As Integer 

Set eventSheet = ThisWorkbook.Sheets("previousEvent") 
Set yearSheet = ThisWorkbook.Sheets("previous12") 
Set eventRange = eventSheet.Range("A3", eventSheet.Range("A3").End(xlDown)) 
Set yearRange = yearSheet.Range("A4", yearSheet.Range("A4").End(xlDown)) 


    For Each gEvent In eventRange 

     i = 0 

     gEvent.Offset(0, 16).Value = gEvent.Value 
     gEvent.Offset(0, 17).Value = gEvent.Offset(0, 1).Value 
     gEvent.Offset(0, 18).Value = gEvent.Offset(0, 2).Value 


     itemCount = Application.WorksheetFunction.CountIf(yearRange, gEvent.Value) 

     For i = 0 To 11 

      itemPY = Application.WorksheetFunction.SumIfs(yearRange.Offset(0, i + 3), yearRange.Value, "=" & gEvent.Value & """, yearRange.Offset(0, 2), " = " & gEvent.Offset(0, 2).Value & """) 

      gEvent.Offset(0, 19 + i).Value = itemPY/Item 

     Next i 

    Next gEvent 


End Sub 

我可以得到任何幫助將是偉大的。

+0

我調整到「=」&gEvent.Value&「」」,但它仍然是打破了最終的結果我打算在字符串中「= ABCD」其中gEvent.Value = ABCD – William

+1

試試這個:'itemPY = Application.WorksheetFunction.SumIfs(yearRange.Offset(0,i + 3),yearRange,gEvent.Value&「」「」「,yearRange.Offset 0,2),gEvent.Offset(0,2).Value&「」「」)' –

+1

這樣做了,謝謝!它僅僅是字符串連接的引號問題嗎? – William

回答

1

沒有必要爲所有報價:

itemPY = Application.WorksheetFunction.SumIfs(yearRange.Offset(0, i + 3), _ 
        yearRange, gEvent.Value, _ 
        yearRange.Offset(0, 2), gEvent.Offset(0, 2).Value) 
+0

這也適用。 simoco,謝謝你們倆! – William