Or
EDITED POST shg woke me up
Option Explicit
Function CountInstances(FindWhat As String, rng As Range) As Integer
Dim PositionOfChar As Integer
Dim HowManyChars As Integer
HowManyChars = 0
PositionOfChar = InStr(1, rng.Value, FindWhat)
Do
If PositionOfChar > 0 Then
CountInstances = CountInstances + 1
PositionOfChar = InStr(PositionOfChar + 1, rng.Value, FindWhat)
Else
Exit Do
End If
Loop
End Function
Or better still with shgs' suggestion
Function CountInstances(FindWhat As String, rng As Range) As Integer
CountInstances = Len(rng.Value) - Len(Replace(rng.Value, FindWhat, ""))
End Function
Called with
NumberOfHyphens = CountInstances("-", Range("B8"))
or in the worksheet as a UDF
The code is now a bit more flexible it will count any instances of a string in a string.
So your code could be on these lines.
Sub YourProcedure()
Dim FileFullName As String, wsName As String
Dim xlWkb As Workbook
Dim xlWks As Worksheet
FileFullName = "K:\Excel Forum\TempOneOffs\Book3.xls"
Set xlWkb = Workbooks.Open(FileFullName) ' opening the workbook to upload
wsName = "Corr-Score" ' setting the sheet with the data needed
Set xlWks = xlWkb.Worksheets(wsName)
With xlWks
Select Case CountInstances("-", .Range("B8"))
Case 2
.Range("B8") = .Range("B8")
Case 1
.Range("B8") = .Range("B6")
Case Else
'do something else
End Select
End With
End Sub
Bookmarks