' 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
來源
2013-03-16 08:52:56
dee
您也可以通過輸入C2的公式,然後雙擊填充柄(右下做到這一點細胞的一角)。 – SomeSillyName 2013-03-15 17:21:59
在單元格C1中鍵入'= COUNTIF(A:A,B1)',然後雙擊填充句柄(按照SomeSillyName的建議)。這是最簡單的方法。 – 2013-03-15 19:44:42