本文介绍了Excel-VBA 中的 Sumifs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 vba 中的 sumifs 有一些问题:

I have some problem with sumifs in 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

我总是收到类型不匹配"错误

I always get a "Type mismatch" error

有人可以帮我修复代码吗?

Could anybody help me to fix the code?

提前致谢.

推荐答案

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").

You can also specify Arg3 as a variant and pass a single-cell range if it has the criteria. Criteria can be True/False (=False), a number (20) or a string (">100").

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

我意识到你想要做什么.Arg3 中的每个单元格都是您要对其执行 SumIf 的单独条件.这是修改后的代码.

I realized what you were trying to do. Each cell in Arg3 is a separate criteria that you want to do SumIf on. Here is the revised code.

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 的大小必须相同.

Note how Arg3 is used in SumIfs Arg3.Cells(i - 1, 1).Value. Also note that Arg1 and Arg2 must be the same size.

这篇关于Excel-VBA 中的 Sumifs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-11 17:46