troubleshooting Question

Convert Macro to Function

Avatar of Alex Campbell
Alex CampbellFlag for United States of America asked on
Microsoft OfficeMicrosoft ExcelMicrosoft Applications
7 Comments1 Solution972 ViewsLast Modified:
While I know there are easier ways to count the number of occurrences of a particular character in a cell, I am learning VBA so I want to take a different approach.

The following is a macro from that prompts you for a character and then it returns how many times that character occurred in a cell or range of cells.

How would you convert this macro into a function that you would give a cell or range of cells and the character to be searched for and it would return the number of occurrences.

The following Visual Basic procedure prompts you for a character (or characters), then searches through the currently selected cell, or range of cells, and displays a message box showing the total number of occurrences of that character or character string. This works for all alphanumeric characters.

Dim Count As Integer
Dim Target As String
Dim Cell As Object
Dim N As Integer

Sub Target_Count()
   Count = 0
   Target = InputBox("character(s) to find?")
   If Target = "" Then GoTo Done
      For Each Cell In Selection
         N = InStr(1, cell.Value, target)
         While N <> 0
            Count = count + 1
            N = InStr(n + 1, cell.Value, target)
      Next Cell
   MsgBox count & " Occurrences of " & target
End Sub 
Saqib Husain

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 7 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros