Countif直到填充特定列中的最后一行

时间:2013-03-15 17:11:22

标签: excel vba

我在完成宏时遇到问题。它使用COUNTIF函数并针对来自B2的数据检查整个A列(A:A - 无排除)。我想在C列中进行自动填充,直到B列中的最后一个值 - 就像下面的图片所示:

enter image description here

任何人都可以帮助我添加到我的代码中以使此自动填充成为可能吗?

Sub Countif()

Range("C2").Select
ActiveCell.FormulaR1C1 = "=COUNTIF(C[-2],RC[-1])"
Selection.AutoFill Destination:=Range("C2:C10"), Type:=xlFillDefault
Range("C2:C10").Select

End Sub

3 个答案:

答案 0 :(得分:1)

如果你想使用VBA尝试下面的代码。只需运行宏,它就会填满B列中的C uptil值。

Sub sample()

Dim LastRowColumnB As Long
LastRowColumnB = Range("B65000").End(xlUp).Row

For i = 2 To LastRowColumnB
    Cells(i, 3) = Application.CountIf(Range("A:A"), Cells(i, 2))
Next
End Sub

答案 1 :(得分:0)

您可以像这样获取列的最后一行:

Dim LastRowColumnB as Long
LastRowColumnB = Activesheet.Cells(Activesheet.Rows.Count, "B").End(xlUp).Row

然后修改自动填充以使用该值。

Selection.AutoFill Destination:=Range("C2:C" & LastRowColumnB), Type:=xlFillDefault

答案 2 :(得分:0)

' COUNTIF(range,criteria)
' {0} will be replaced with range address
' {1} with criteria
Private Const COUNTIF_TEMPLATE As String = "=COUNTIF({0},{1})"
Private Const FIRST_DATA_ROW As Integer = 2
Private Const TARGET_COLUMN As Byte = 3

Public Sub InsertFormulaCountIf()
    ' replace ActiveSheet with your target sheet if necessary
    With ActiveSheet
        Dim lastRowColumnA As Long
        Dim lastRowColumnB As Long

        lastRowColumnA = .Range("A" & .Rows.Count).End(xlUp).Row
        lastRowColumnB = .Range("B" & .Rows.Count).End(xlUp).Row

        Dim formulaText As String
        Dim targetRangeAddress As String
        targetRangeAddress = "A" & FIRST_DATA_ROW & ":A" & lastRowColumnA ' e.g. A2:A500
        formulaText = Replace(COUNTIF_TEMPLATE, "{0}", targetRangeAddress)

        Dim rowIndex As Long
        For rowIndex = FIRST_DATA_ROW To lastRowColumnB
            .Cells(rowIndex, TARGET_COLUMN).Formula = Replace(formulaText, "{1}", "B" & rowIndex)
        Next rowIndex
    End With

End Sub