用于计算列中特定值/字符串数的宏

时间:2013-10-26 11:45:35

标签: excel excel-vba vba

我正在尝试创建一个宏来计算给定列中的特定值。例如,我想计算G列中包含“candy”的所有单元格的数量。我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

怎么样:

Sub dural()
    Dim s As String
    Dim r As Range
    Dim wf As WorksheetFunction
    Set wf = Application.WorksheetFunction
    s = "candy"
    Set r = Range("G:G")
    MsgBox wf.CountIf(r, s)
    '
    ' and if you want to count phrases including candy then:
    '
    s = "*" & s & "*"
    MsgBox wf.CountIf(r, s)
End Sub

修改

并将结果存储在工作表单元格中:

Sub dural()
    Dim s As String
    Dim r As Range
    Dim wf As WorksheetFunction
    Set wf = Application.WorksheetFunction
    s = "candy"
    Set r = Range("G:G")
    s = "*" & s & "*"
    [H3] = wf.CountIf(r, s)
End Sub