2016-11-25 111 views
3

我在VBA中有一些問題sumifsSUMIFS在Excel的VBA

Dim Arg1 As Range 'the range i want to sum 
Dim Arg2 As Range 'criteria range 
Dim Arg3 As Variant 'the criteria 

Set Arg1 = ThisWB.Sheets("Sheet1").Range("B2:B100") 
Set Arg2 = ThisWB.Sheets("Sheet1").Range("C1:C100") 
Set Arg3 = ThisWB.Sheets("Sheet2").Range("A2:A12") 

For i = 2 To 12 
Workbooks("x.xlsx").Worksheets("Sheet2").Cells(i, LastColumn) _ 
= Application.WorksheetFunction.SumIfs(Arg1, Arg2, Arg3) 


Next 

我總是得到一個「類型不匹配」錯誤

任何人可以幫我修復代碼?

預先感謝您。

回答

2

https://msdn.microsoft.com/en-us/library/office/ff193011.aspx

Sub test() 
    Dim Arg1 As Range 'the range i want to sum 
    Dim Arg2 As Range 'criteria range 
    Dim Arg3 As Variant 'the criteria 

    'Arg1 and Arg2 must be the same size 
    Set Arg1 = Sheets("Sheet1").Range("B2:B100") 
    Set Arg2 = Sheets("Sheet1").Range("C2:C100") 

    'this is the criteria 
    Arg3 = "=False" 

    Dim ws As Worksheet 
    Set ws = ActiveSheet 
    Dim i As Integer 
    For i = 2 To 12 
     ws.Cells(i, 8).Value = Application.WorksheetFunction.SumIfs(Arg1, Arg2, Arg3) 
    Next 
End Sub 

還可以指定ARG3作爲變體,並通過單小區範圍,如果它具有標準。標準可以是True/False(= False),數字(20)或字符串(「> 100」)。

Dim Arg3 As Variant 'the criteria 
    Arg3 = Sheets("Sheet2").Range("A2") 

編輯:我意識到你正在嘗試做什麼。 Arg3中的每個單元格都是一個單獨的標準,您要執行SumIf。這是修改後的代碼。

Sub test2() 
    Dim ThisWB As Workbook: Set ThisWB = ThisWorkbook 
    Dim i As Integer 
    Dim LastColumn As Integer: LastColumn = 3 

    Dim Arg1 As Range 'the range i want to sum 
    Dim Arg2 As Range 'criteria range 
    Dim Arg3 As Range 'the criteria (range) 

    Set Arg1 = ThisWB.Sheets("Sheet1").Range("B2:B100") 
    Set Arg2 = ThisWB.Sheets("Sheet1").Range("C2:C100") 
    Set Arg3 = ThisWB.Sheets("Sheet2").Range("A2:A12") 

    For i = 2 To 12 
     Workbooks("x.xlsx").Worksheets("Sheet2").Cells(i, LastColumn) _ 
      = Application.WorksheetFunction.SumIfs(Arg1, Arg2, Arg3.Cells(i - 1, 1).Value) 
    Next 
End Sub 

請注意在SumIfs Arg3.Cells(i - 1, 1).Value中如何使用Arg3。另請注意,Arg1和Arg2必須具有相同的大小。

+0

我嘗試了溶劑化,但它不起作用:下標超出範圍。你有什麼主意嗎?預先感謝您 –

+0

您需要找出哪條線和哪個項目超出範圍。你真的有一個名爲「x.xlsx」的工作簿已經打開嗎?你有「Sheet2」嗎?等代碼工作得很好,所以有些不同。如果你不能解決問題另一個問題。你的SumIf問題(不匹配錯誤)已經解決了。現在您正在詢問超出範圍的錯誤;這是一個單獨的問題,需要成爲一個單獨的問題。 –

+0

是的,你是對的。我在嘗試代碼時犯了一個錯誤。現在我再次嘗試一次,注意力更強,它正在工作。所以非常感謝! –