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),然后find6,5,… 1。 任何帮助和/或build议将不胜感激!

以下将写出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 

你可以做到这一点

 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 

除非你真的需要在单元格中的公式。