vba中的Sumif函数以及如何在公式中使用动态范围

时间:2016-06-09 05:15:49

标签: excel-vba vba excel

我通过excel vba尝试了sumif功能但是我得到了#value"错误。

Sub xd()
R_lastrow = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
R_lastcolumn = Sheets(1).Cells(1, Columns.Count).End(xlToLeft).Column

o_lastrow = Sheets(2).Cells(Rows.Count, 1).End(xlUp).Row
o_lastcolumn = Sheets(2).Cells(1, Columns.Count).End(xlToLeft).Column

For k = 2 To o_lastrow
    For j = 2 To o_lastcolumn
Sheets("Sheet2").Cells(k, j).Value = Sheets("Sheet2").Evaluate("SUMIF(Sheet1!&range(cells(2,R_lastrow),cells(2,R_lastcolumn)),range(1,j),Sheet1!&range(cells(j,R_lastrow))")
    Next j
Next k
End Sub

你能否告诉我我错在哪里

1 个答案:

答案 0 :(得分:1)

您需要将范围地址替换为公式。

未测试:

Sub xd()

    Const f As String = "SUMIF(Sheet1!<r1>,<r2>,Sheet1!<r3>)"

    R_lastrow = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
    R_lastcolumn = Sheets(1).Cells(1, Columns.Count).End(xlToLeft).Column

    o_lastrow = Sheets(2).Cells(Rows.Count, 1).End(xlUp).Row
    o_lastcolumn = Sheets(2).Cells(1, Columns.Count).End(xlToLeft).Column

    f1 = Replace(f, "<r1>", Range(Cells(2, R_lastrow), _
                                  Cells(2, R_lastcolumn)).Address(False, False))

    For k = 2 To o_lastrow
        For j = 2 To o_lastcolumn
            frm = Replace(f1, "<r2>", Cells(1, j).Address(False, False))
            frm = Replace(frm, "<r3>", Cells(j, R_lastrow).Address(False, False))
            Debug.Print frm
            Sheets("Sheet2").Cells(k, j).Value = Sheets("Sheet2").Evaluate(frm)
        Next j
    Next k
End Sub