CountIf工作表函数的替代方案

时间:2016-06-24 17:46:05

标签: excel vba excel-vba countif

我正在尝试使用CountIf WorksheetFunction来显示有多少值高于和低于给定值。唯一的问题是,我之前使用过滤器,使用的范围是破碎的范围。我刚刚了解到CountIf函数只能接受一个实数范围。有替代方案,或者可能是解决方法吗?我的射程非常不稳定,有许多休息时间。

 ElseIf CWYes = True Then
        Worksheets("Modified Item Extract").Range("$A$1:$CL$293662").AutoFilter Field:=1, Criteria1:="" & PBH.Value
    Dim y As Double
    Dim z As Double
            PricePerKG = POCost
            Set ws = ActiveWorkbook.Worksheets("Modified Item Extract")
            Set relevant_array = ws.Range(ws.Range("B2"), ws.Range("B2").End(xlDown)).SpecialCells(xlCellTypeVisible)

            y = WorksheetFunction.PercentRank(relevant_array, POCost)
            Percentile = Format(y, "0.00%")
                If y > 0.7 Then Warning = "WARNING: your price is above the 70th percentile of items in the same PBH"
                If y < 0.3 Then Warning = "WARNING: your price is below the 30th percentile of items in the same PBH"
                If y > 0.3 And y < 0.7 Then Warning = "Carry on: your price is between the 30th and 70th percentile of items in the same PBH"
                If y = 0 Then MsgBox "The price you provided is out of the range of the PBH"

            Set ws = ActiveWorkbook.Worksheets("Modified Item Extract")

            Set relevant_range = ws.Range(ws.Range("B2"), ws.Range("B2").End(xlDown)).SpecialCells(xlCellTypeVisible)
            MsgBox relevant_range.Address
            z = WorksheetFunction.CountIf(relevant_range, "<" & POCost)
            PriceAbove = z

1 个答案:

答案 0 :(得分:0)

一种选择是遍历细胞:

For each relevant_cell in relevant_range
   If relevant_cell < POCost Then PriceAbove = PriceAbove + 1
Next

另一种选择是再次过滤数据集:

  Set ws = ActiveWorkbook.Worksheets("Modified Item Extract")

  With ws

      With .Range("$A$1:$CL$293662")
          .AutoFilter Field:=1, Criteria1:="" & PBH.Value
          .AutoFilter Field:=2, Criteria1:="<" & POCost
      End With

      Dim PriceAbove As Double
      Price Above = .Range(.Range("B2"),.Range("B2").End(xlDown)).SpecialCells(xlCellTypeVisible).Rows.Count

  End With