簡體   English   中英

計數直到填充特定列的最后一行

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

我在完成宏時遇到問題。 它使用COUNTIF函數,並對照來自B2的數據檢查整個A列(A:A-不排除)。 我想在C列中進行自動填充,直到B列中的最后一個值-如下圖所示:

在此處輸入圖片說明

誰能幫助我,我應該在代碼中添加些什么才能使自動填充成為可能?

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

如果您想使用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

您可以像這樣獲得一列的最后一行:

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

然后修改自動填充以使用該值。

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