2013-03-15 75 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 
相關問題