VBA - Countif错误'438'

时间:2016-04-24 08:51:33

标签: vba error-handling

我正在尝试在VBA中做COUNTIF而我正在获得一些resom错误'438',我不知道为什么。

Option Explicit

Sub tools()
'

With Worksheets("Plans")
    .Range("a:ar").AutoFilter Field:=2, Criteria1:="=Cv", Operator:=xlOr, Criteria2:="=Se"
    .rows("6:6").Select
    .Range(Selection, Selection.End(xlDown)).Select
    .Selection.Delete Shift:=xlUp
    .ShowAllData
    .Range("A2:A" & .Cells(rows.Count, "e").End(xlUp).Row).FormulaR1C11 = "=COUNTIF(c[5],RC[5])"
    .Range("A2:a" & .Cells(rows.Count, "e").End(xlUp).Row) = Range("A2:a" & .Cells(rows.Count, "e").End(xlUp).Row).Value2
End With

End Sub

1 个答案:

答案 0 :(得分:2)

有两个错误,每个错误都会导致'38'错误:

.Selection.Delete Shift:=xlUp

因为Selection不是Worksheet对象的有效属性

.FormulaR1C11 

只是一个错字,因为它应该是

FormulaR1C1

除此之外,还有一些良好的编码习惯,如:

  • 避免使用SelectSelection

    设置并使用对象(范围)的直接引用

  • 使用With关键字

    避免重复相同的长引用

    这样可以避免输入错误

  • 避免引用整个列或行

    并限制实际使用的单元格的范围

    这尤其在使用像COUNTIF

  • 这样的工作表函数时

所以这里是为错误修改的代码以及上面提到的良好编码习惯

Option Explicit

Sub tools()

With Worksheets("Plans")
    .Range("a:ar").AutoFilter Field:=2, Criteria1:="=Cv", Operator:=xlOr, Criteria2:="=Se"

    With .rows("6:6")
        Range(.Cells, .End(xlDown)).Delete Shift:=xlUp
    End With

    .ShowAllData

    With .Range("A2:A" & .Cells(rows.Count, "e").End(xlUp).Row)
        .FormulaR1C1 = "=COUNTIF(R1C[5]:R" & .rows(.rows.Count).Row & "C[5],RC[5])"
        .Value = .Value2
    End With
End With

End Sub