CountIf具有可变范围

时间:2014-04-07 16:23:04

标签: excel vba excel-vba countif

我正在尝试使用COUNTIF编写宏来查找数字出现在某个范围内的次数。它是一个评级列表,从1到7.问题是行数每次都会有所不同,以及评级所在的列。

我之前确实写过这个,但是当我的硬盘崩溃时我丢失了所有代码!所以我知道这可以做到,但我不记得我是怎么做到的。这是我的代码和评论:

'find the cell called "Rating".  In this example, it will be in $E$13
Cells.Find(What:="Rating", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=True).Activate

'This will be $E$13
Top = ActiveCell.Address

'This will be 5, for column E
CurrentColumn = ActiveCell.Column

'go to the bottom cell of the range
Cells(50000, CurrentColumn).End(xlUp).Select

'This will be $E$37
Bottom = ActiveCell.Address

'Combine the top and bottom to make the range, which will be $E$13:$E$37
RangeToSelect = Top & ":" & Bottom

'Under the range, go down 4 cells and do a COUNTIF for the numbers 7 to 1
ActiveCell.Offset(4, 0).Range("A1").Select

For xx = 7 To 1 Step -1
ActiveCell.FormulaR1C1 = "=COUNTIF(" & RangeToSelect & "," & xx & ")"
ActiveCell.Offset(1, 0).Range("A1").Select
Next xx

抛出错误的代码是:

ActiveCell.FormulaR1C1 = "=COUNTIF(" & RangeToSelect & "," & xx & ")"

第一个单元格最终应为= COUNTIF($ E $ 13:$ E $ 37,7),然后找到6,5,... 1。任何帮助和/或建议将不胜感激!!!

2 个答案:

答案 0 :(得分:1)

你可以这样做

Dim RangeToSelect AS Range

Set RangeToSelect = ActiveWorksheet.Range(Top,Bottom)

For xx = 7 To 1 Step -1
    ActiveCell.Value = Application.WorksheetFunction.CountIf(RangeToSelect,xx)
    ActiveCell.Offset(1, 0).Select
Next xx

除非你真的需要细胞中的公式。

答案 1 :(得分:1)

以下将写出countif的结果:

Option Explicit
Sub Stack()

Dim MySheet As Worksheet
Dim FoundRng As Range, RangeToSelect As Range
Dim LastRow As Long, xx As Long

'assign our sheet to avoid confusion
Set MySheet = ThisWorkbook.ActiveSheet

'locate the "Rating" cell
Set FoundRng = MySheet.Cells.Find(What:="Rating", LookAt:=xlWhole, MatchCase:=False)
If FoundRng Is Nothing Then
    MsgBox ("No matching cell found, exiting sub!")
    Exit Sub
End If

'determine the boundaries of the target range for populating the formula
LastRow = MySheet.Cells(50000, FoundRng.Column).End(xlUp).Row

'assign the target range
Set RangeToSelect = Range(MySheet.Cells(FoundRng.Row, FoundRng.Column), MySheet.Cells(LastRow, FoundRng.Column))

'write out the countif results
MySheet.Cells(LastRow + 4, FoundRng.Column).Select
For xx = 7 To 1 Step -1
    ActiveCell.Value = Application.WorksheetFunction.CountIf(RangeToSelect, xx)
    ActiveCell.Offset(1, 0).Select
Next xx

End Sub