Consulting

Results 1 to 5 of 5

Thread: Countif in VBA Module

  1. #1
    VBAX Newbie
    Joined
    Aug 2022
    Posts
    3
    Location

    Countif in VBA Module

    Hi,
    I have a column of just under 62,000 rows where I am trying to get an accurate count for each value on each row. If I type =COUNTIF($J$2:$J$61948,J2) in cell K2 and copy it down, then it works correctly. However, I want to be able to run it using VBA, but it keeps blowing up on me. Here is the module that I am using:


    Sub PrimaryCount()
    Dim LastRow as long
    LastRow = Cells(Rows.Count, 13).End(xlUp).Row
    Range("K2:K" & LastRow).Value = "=COUNTIF($J$2:$J$& LastRow,J2)" <- 1004 error 
    End Sub

    When I try to run the code I get a Run-time error ‘1004’: Application-defined or object-defined error. After I get the error, if I highlight the row I get a “<type mismatch>” on what appears to be the second "LastRow" underlined above. What do I need to fix to make this work using VBA – or – is there a better option?

    Mark
    Last edited by Aussiebear; 08-26-2022 at 12:10 PM. Reason: Added code tags to supplied code

  2. #2
    VBAX Expert
    Joined
    Aug 2004
    Posts
    810
    Location
    see if this fixes your problem
    Range("K2:K" & LastRow).Formula = "=COUNTIF($J$2:$J$" & LastRow & ",J2)"

  3. #3
    Knowledge Base Approver VBAX Wizard p45cal's Avatar
    Joined
    Oct 2005
    Location
    Surrey UK
    Posts
    5,876
    try:
    Sub PrimaryCount()
    Dim LastRow As Long
    LastRow = Cells(Rows.Count, 13).End(xlUp).Row
    With Range("K2:K" & LastRow)
      .FormulaR1C1 = "=COUNTIF(R2C10:R" & LastRow & "C10,RC[-1])"
      .Value = .Value 'convert to plain values
    End With
    End Sub
    or:
    Sub PrimaryCount2()
    Dim LastRow As Long
    LastRow = Cells(Rows.Count, 13).End(xlUp).Row
    Range("K2:K" & LastRow).Value = Evaluate("COUNTIF(J2:J" & LastRow & ",J2:J" & LastRow & ")")
    End Sub
    p45cal
    Everyone: If I've helped and you can't be bothered to acknowledge it, I can't be bothered to look at further posts from you.

  4. #4
    VBAX Newbie
    Joined
    Aug 2022
    Posts
    3
    Location
    That did it!
    Thank you, so much for your help - I really appreciate it!
    Mark

  5. #5
    VBAX Newbie
    Joined
    Aug 2022
    Posts
    3
    Location
    Thank you, p45cal! Both of your ides worked, too. I appreciate your help.
    Mark

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •