可变总和范围

时间:2018-07-09 07:41:07

标签: excel-vba variables sumifs vba excel

我得到

  

编译错误:类型不匹配

我的代码有误。该代码背后的想法是使可变的总和范围取决于j循环。请不要批评我,因为我还是VBA的新手。请帮忙。

Sub eiegraanGB()
    Application.ScreenUpdating = False

    Dim i As Integer
    Dim j As Integer
    Dim arg1 As Range
    Dim arg2 As Range
    Dim arg3 As Range
    Dim arg4 As Range
    Dim arg5 As Range
    Dim arg6 As Range
    Dim arg7 As Range
    Dim arg8 As Range
    Dim arg9 As Range
    Dim arg10 As Range
    Dim arg11 As Range
    Dim arg As Integer
    Dim k As Range

    Worksheets("HR Grn Bedryf").Activate

    Set arg2 = Worksheets("Sorted Data").Range("I:I")
    Set arg3 = Worksheets("Sorted Data").Range("M:M")
    Set arg4 = Worksheets("Sorted Data").Range("O:O")
    Set arg5 = Worksheets("Sorted Data").Range("N:N")
    Set arg6 = Worksheets("Sorted Data").Range("P:P")
    Set arg7 = Worksheets("Sorted Data").Range("J:J")
    Set arg8 = Worksheets("Sorted Data").Range("A:A")
    Set arg10 = Worksheets("Sorted Data").Range("B:B")

    For j = 2 To 7
        Set k = arg & j
        For i = 184 To 2386
            Set arg9 = Cells(i, 1)
            Set arg11 = Cells(i, 12)
            Cells(i, 1).Select
            If ActiveCell.Value = "BVH EIE GRAAN" Or ActiveCell.Value = "AANKOPE EIE REK. GRN" Or ActiveCell.Value = "EVH EIE GRAAN" Or ActiveCell.Value = "VERKOPE EIE GRAAN" Then
                Cells(i, j) = Application.WorksheetFunction.SumIfs(k, arg8, arg9, arg10, arg11)
            Else

            End If  
        Next i    
    Next j

    Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:1)

您需要为此使用数组。将arg定义为1到11之间的数组:

Dim arg(1 To 11) As Range
Set arg(2) = Worksheets("Sorted Data").Range("I:I")

然后您可以像这样使用它:

Set k = arg(j)

注意:我建议您阅读How to avoid using Select in Excel VBA,以使您的代码更快,更稳定。

我还建议使用Long代替Integer Excel的行数超过Integer不能处理的行,并且在VBA中使用Integer根本没有好处。 / p>

相关问题