' 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