根据另一个工作表中的列计算项目

时间:2016-12-19 17:33:21

标签: vba excel-vba excel

尝试使用vba编写countifs函数但得到对象错误不支持此属性或方法。 (运行时错误438)

Sub counters()

    Dim rng, rng2, rng3, rng4 As Range
    Dim lrow, lr, lr2, lr3, lr4 As Long
    Dim ws, ws1 As Worksheet

    Set ws = Sheets("Data")
    Set ws1 = Sheets("Table E-1 Zip Codes PIF")

    lr = ws.Cells(Cells.Rows.Count, "D").End(xlUp).Row
    lr2 = ws.Cells(Cells.Rows.Count, "X").End(xlUp).Row
    lr3 = ws.Cells(Cells.Rows.Count, "Y").End(xlUp).Row
    lr4 = ws.Cells(Cells.Rows.Count, "AE").End(xlUp).Row
    lrow = ws1.Cells(Cells.Rows.Count, "B").End(xlUp).Row

    'zip code
    Set rng = ws.Range("D2:D" & lr)
    'county
    Set rng2 = ws.Range("X2:X" & lr2)
    'Region
    Set rng3 = ws.Range("Y2:Y" & lr3)
    'policy form
    Set rng4 = ws.Range("AE2:AE" & lr4)

For i = 5 To lrow - 1
Worksheets("Table E-1 Zip Codes PIF").Cells(i, 4).Value = Application.WorksheetFunction.CountIfs(ws.rng, ws1.Cells(i, 2).Value, ws.rng2, ws1.Cells(i, 3).Value, ws.rng3, "NW", ws.rng4, "Basic Choice")
Next i

End Sub

Excel功能正常但需要使用vba自动执行该过程。尝试录制宏但它提供了参考,并且不确定如何重新编写范围代码(ws.Range(“x2:x”& lr))。所有的rng都有相同数量的数据(行),所以我不确定每次都需要定义它。

我希望我的结果在表E-1 ...表中从D5到N-1。我使用For i = 5 To lrow - 1,因为在最后一行有一个总数。

在表E-1表中,D列有一个邮政编码列表,E栏列有我想要匹配的县。

1 个答案:

答案 0 :(得分:1)

除了您使用CountIfs功能的方式外,由于您的数据没有屏幕截图,因此下面的代码会处理您的运行时错误。

运行时错误说明:

1.错误的声明,Dim ws, ws1 As Worksheet应为Dim ws As Worksheet, ws1 As Worksheet,否则ws未定义为Worksheet。所有变量声明都是如此。

2.查找列中的最后一行:lr = ws.Cells(Cells.Rows.Count, "D").End(xlUp).Row错误,应为lr = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row

3.Like @Scott Holtzman在他的评论中写道,因为你已经在前面的行中设置了rng,(Set rng = ws.Range("D2:D" & lr)),那么它应该只与rng一起使用而不是ws.rng

4.要改进和清理代码,您可以在代码的开头使用With ws,并将大部分相关对象嵌套在下面。

"清洁"代码

Option Explicit

Sub counters()

Dim rng As Range, rng2 As Range, rng3 As Range, rng4 As Range
Dim lrow As Long, lr As Long, lr2 As Long, lr3 As Long, lr4 As Long
Dim ws As Worksheet, ws1 As Worksheet

Set ws = Sheets("Data")
Set ws1 = Sheets("Table E-1 Zip Codes PIF")

' last row in Column B in "Table E-1 Zip Codes PIF" sheet
lrow = ws1.Cells(ws1.Rows.Count, "B").End(xlUp).Row

With ws
    lr = .Cells(.Rows.Count, "D").End(xlUp).Row
    lr2 = .Cells(.Rows.Count, "X").End(xlUp).Row
    lr3 = .Cells(.Rows.Count, "Y").End(xlUp).Row
    lr4 = .Cells(.Rows.Count, "AE").End(xlUp).Row

    'zip code
    Set rng = .Range("D2:D" & lr)
    'county
    Set rng2 = .Range("X2:X" & lr2)
    'Region
    Set rng3 = .Range("Y2:Y" & lr3)
    'policy form
    Set rng4 = .Range("AE2:AE" & lr4)

    For i = 5 To lrow - 1
        ws1.Cells(i, 4).Value = Application.WorksheetFunction.CountIfs(rng, ws1.Cells(i, 2).Value, rng2, ws1.Cells(i, 3).Value, rng3, "NW", rng4, "Basic Choice")
    Next i

End With

End Sub