简体   繁体   中英

Macro to count number of specific values/strings in column

I am trying to create a macro that will count specific values in a given column. For example, I want to count the number of all the cells in column G that contain "candy". How would I go about doing this?

How about:

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

Edit :

and to store the result in a worksheet cell:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM