count occurrence of string within string using VBA

almagg

Well-known Member
Joined
Aug 21, 2002
Messages
705
i want to count the number of times a string appears in a string.
sy for example "Excel"

i thought this would work but i get an 'Object Required' when it starts
and 'CountIf' is highlighted.

Dim myfile
Dim mycount

myfile = InputBox("Enter the file name.")

mycount = WorksheetFunction.CountIf(myfile, "*Excel*")
MsgBox "The text 'Excel' appeared" & mycount & "times in the file name."
 

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
GetOpenFileName is a better way to get a filename, but to answer your question:

Code:
Sub test()
Dim myfile As String
Dim mycount As Long

myfile = InputBox("Enter the file name.")
mycount = UBound(Split(myfile, "Excel"))
MsgBox mycount

End Sub
 
Upvote 0
try this

Code:
Sub thing()
    str1 = "excel"
    str2 = "My Excel skills are excellent"
    MsgBox (Len(str2) - Len(Replace(LCase(str2), LCase(str1), ""))) / Len(str1)
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,534
Messages
6,179,390
Members
452,909
Latest member
VickiS

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top