在函数中多次使用时,CountIf无法按预期工作

时间:2013-11-04 16:18:24

标签: excel vba excel-vba excel-2010

您好我正在尝试运行以下代码来计算某些内容出现在工作表中的次数。

Sub test()
  ' passes in what sheet (Sheet1) to search and which row (5) to write the results
  dummy = CountExample("Sheet1", 5)
End Sub

Function CountExample(Sheet As String, RowPopulate As Integer)
  Sheets(Sheet).Select ' Selects the appropriate sheet to search through
  Dim tmp As Integer

  ' Search for find1
  tmp = Application.WorksheetFunction.CountIf(Cells, "find1")
  Sheets("Recording Sheet").Select
  Range("C" & RowPopulate).Value = tmp ' Update and write the value in C5
  tmp = 0  'this does not seem to do anything


  ' something wrong with this one find2 should have 39 matches not 15
  ' Search for find2
  tmp = Application.WorksheetFunction.CountIf(Cells, "find2")
  Sheets("Recording Sheet").Select
  Range("E" & RowPopulate).Value = tmp ' Update and write the value in E5


End Function

当我只运行代码来搜索find2时(在删除搜索find1的代码之后),我得到了39个匹配,这是正确的,但如果我运行上面的代码,我会得到15个匹配的find2。

我似乎无法弄清楚为什么会这样。

由于

3 个答案:

答案 0 :(得分:3)

工作表/范围对象的范围不正确。一个常见的错误,以及避免依赖SelectActivate方法等构造的一个原因,除非另有明确说明,否则范围对象始终引用ActiveSheet

尝试这样做(根据Garys的建议编辑使用子程序而不是函数):

Sub test()
  ' passes in what sheet (Sheet1) to search and which row (5) to write the results
  CountExample "Sheet1", 5
End Sub


Sub CountExample(Sheet As String, RowPopulate As Integer)
   ' Selects the appropriate sheet to search through
  Dim tmp As Integer
  Dim ws as Worksheet
  Dim wsRecord as Worksheet

  Set ws = Worksheets(Sheet)
  Set wsRecord = Worksheets("Recording Sheet")

      ' Search for find1
      tmp = Application.WorksheetFunction.CountIf(ws.Cells, "find1")
      wsRecord.Range("C" & RowPopulate).Value = tmp ' Update and write the value in C5
      tmp = 0  'this does not seem to do anything


      ' something wrong with this one find2 should have 39 matches not 15
      ' Search for find2
      tmp = Application.WorksheetFunction.CountIf(ws.Cells, "find2")
      wsRecord.Range("E" & RowPopulate).Value = tmp ' Update and write the value in E5


End Sub

答案 1 :(得分:1)

  1. 您需要Sub而不是Function,因为您想要更改一组单元格而不是返回单个值

答案 2 :(得分:0)

您正在使用Sheets("Recording Sheet").Select切换到“记录表”,但您没有切换回Sheet。所以第二个CountIf发生在“记录表”上。