0

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

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 匹配项。

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

谢谢

4

3 回答 3

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
于 2013-11-04T16:23:42.793 回答
1
  1. 您需要 Sub 而不是 Function 因为您想要更改一组单元格而不是返回单个值
于 2013-11-04T16:23:44.477 回答
0

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

于 2013-11-04T16:22:50.570 回答