制作" Countif"工作表函数变量

时间:2018-01-31 08:52:17

标签: excel vba excel-vba

我有一个代码可以计算范围内的单元格,如果有数字的话。计数的细胞总数将显示在第3行。我现在的问题是公式不可变,我也不知道如何制作它。 如果我输入此代码,第3行将报告所有相同的结果(来自第一列数据)。希望有人可以帮助我!!

Sub Six_Continue()

    Dim Rng As Range
    Dim LastClm As Long


    With ActiveSheet
        LastClm = .Cells(1, .Columns.Count).End(xlToLeft).Column
        Set Rng = Range(.Cells(3, 3), .Cells(3, LastClm))
        Rng.Value = Application.WorksheetFunction.CountIf(Range("C5", "C" & Cells(Rows.Count, 5).End(xlUp).Row), "<>?")
    End With

End Sub

2 个答案:

答案 0 :(得分:2)

即使不包含数字,您的CountIf也会对单元格进行计数。使用Count可确保仅考虑包含数字的单元格。

Sub Six_Continue()

    Dim Rng As Range
    Dim LastClm As Long
    Dim myClm As Long


    With ActiveSheet
        LastClm = .Cells(1, .Columns.Count).End(xlToLeft).Column
        For myClm = 1 To LastClm
            Set Rng = .Cells(3, myClm)
            Rng.Value = Application.WorksheetFunction.Count(Range(.Cells(5, myClm), .Cells(.Cells(Rows.Count, myClm).End(xlUp).Row, myClm)))
        Next myClm
    End With

End Sub

答案 1 :(得分:0)

试试这个修改过的版本:

Sub Six_Continue()

Dim Rng As Range
Dim LastClm As Long, i As Long
LastClm = Cells(1, Columns.Count).End(xlToLeft).Column

For i = 1 To LastClm
    Cells(3, i).Value = Application.WorksheetFunction.CountIf(Range(Cells(1, i), Cells(2, i)), "<>?")
Next
End Sub