VBA sumif具有可变范围

时间:2016-05-04 07:35:13

标签: vba excel-vba excel

我是VBA的新手,所以我得请你帮忙。 下面,我得到了VBA代码,它应该根据活动表第一列的值来汇总来自不同表单[AB]的数据。行数和列数是可变的,因此单元格地址必须是绝对的。

Sub sumif_test

Range("A1").Select
Selection.End(xlDown).Select
abc = ActiveCell.Row
Selection.End(xlUp).Select
Selection.End(xlToRight).Select

ActiveCell.Offset(1, 1).Select

Dim mycrit As Variant
Dim myval As Variant
Dim CritRng As Range
Dim SumRng As Range

Set CritRng = Worksheets("AB").Range("A:A")
Set SumRng = Worksheets("AB").Range("N:N")

c = ActiveCell.Column
r = ActiveCell.Row

For r = 2 To abc - 2
mycrit = Cells(r, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
myval = Cells(r, c).Address(RowAbsolute:=False, ColumnAbsolute:=False)
myval = Application.WorksheetFunction.SumIf(CritRng, mycrit, SumRng)

Next r

End sub

使用此代码我无法获得任何结果。

2 个答案:

答案 0 :(得分:0)

您需要范围,您需要设置它们。在您的代码中,如果您在myval之后编写debug.print,如下所示:

For r = 2 To abc - 2
   mycrit = Cells(r, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
   myval = Cells(r, c).Address(RowAbsolute:=False, ColumnAbsolute:=False)
   myval = Application.WorksheetFunction.SumIf(CritRng, mycrit, SumRng)
   debug.print myval
Next r

End sub

您可能会在即时窗口中获得一些结果。 CTRL + G。 为了获得一些结果,请尝试:

For r = 2 To abc - 2
    mycrit = Cells(r, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
    myval = Cells(r, c).Address(RowAbsolute:=False, ColumnAbsolute:=False)
    myval = Application.WorksheetFunction.SumIf(CritRng, mycrit, SumRng)
    Cells(r,c) = myval
Next r

End sub

最后 - 2件事 - try to avoid usage of select并格式化你的代码:) Here你可以找到一些与VBA相关的sumif的例子。

答案 1 :(得分:0)

尽量避免使用select语句。还学习使用Application.ScreenUpdating属性来加速代码(这会禁用每次写入Excel工作表之间的屏幕刷新,并在最后更新所有内容,使其更快)

Sub sumif_test()
    Dim ws As Worksheet
    Dim NoCol As Integer, NoRow As Integer
    Dim CritRng As Range, SumRng As Range

    Application.ScreenUpdating = False

    Set ws = Worksheets("AB")

    With ws
        NoRow = .Cells(.Cells.Rows.Count, 1).End(xlUp).Row
        NoCol = .Cells(1, .Cells.Columns.Count).End(xlToLeft).Column
        Set CritRng = .Range("A:A")
        Set SumRng = .Range("N:N")
    End With

    For r = 2 To NoRow
        Cells(r, NoCol) = WorksheetFunction.SumIf(CritRng, Cells(r, 1), SumRng)
    Next r

    Application.ScreenUpdating = True
End Sub

我已重写您的代码以避免使用select语句。请看一下它,看看你是否能弄清楚每个部分的作用。