2013-03-15 77 views
0

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

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 
+1

您也可以通过输入C2的公式,然后双击填充柄(右下做到这一点细胞的一角)。 – SomeSillyName 2013-03-15 17:21:59

+0

在单元格C1中键入'= COUNTIF(A:A,B1)',然后双击填充句柄(按照SomeSillyName的建议)。这是最简单的方法。 – 2013-03-15 19:44:42

回答

1

如果你想实现使用VBA请尝试下面的代码。只要运行宏并将其WUD 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 
+0

@ALL--谢谢大家以下的帖子。所有的代码都可以工作,但user2063626发布的代码似乎是最快的方式,也是最简单的方式(因为它也将countif公式替换为值。) – mgunia 2013-03-18 08:56:21

+0

乐意提供帮助!!! :-) – 2013-03-18 10:54:03

0

你可以得到一个列的最后一行,像这样:

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

,然后修改您的自动填充使用该值。

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