简体   繁体   English

计数直到填充特定列的最后一行

[英]Countif until the last row in specific column is populated

I have a problem with finishing my macro. 我在完成宏时遇到问题。 It uses the COUNTIF function and checks the whole A column (A:A - no exclusions) against the data from B2. 它使用COUNTIF函数,并对照来自B2的数据检查整个A列(A:A-不排除)。 I would like to make the autofill in the C column until the last value in the B column - just like presented on the picture below: 我想在C列中进行自动填充,直到B列中的最后一个值-如下图所示:

在此处输入图片说明

Could anyone help me what should I add to my code to make this autofill possible?? 谁能帮助我,我应该在代码中添加些什么才能使自动填充成为可能?

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

If you wanna achieve using VBA try below code. 如果您想使用VBA,请尝试以下代码。 Just Run the macro and it wud fill up the column C uptil values in column B. 只需运行宏,它就会填充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

You can get the last row of a column like so: 您可以像这样获得一列的最后一行:

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

and then modify your autofill to use that value. 然后修改自动填充以使用该值。

Selection.AutoFill Destination:=Range("C2:C" & LastRowColumnB), Type:=xlFillDefault
' 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM