直接上例子
A1=13256598,b1=6135 c1=5
其中1,3 ,6各出现一次,5出现2次,加起来等于5
特别说明b1不一定等于4个字符。有时3个,也有可能5个
如果是b1等于1个字符的我知道,可以用instr
多字符要怎么写
提供一个获取子字符串在父字符串中出现的次数的通用方法:
' ##############################################' [功能描述] 获取子字符串在父字符串中出现的次数.
' [参数列表] 1. strParent 父字符串;
' 2. strChild 子字符串.
' [返回类型] Long.
' ##############################################
Public Function GetRepeatedTimes(ByVal strParent As String, _
ByVal strChild As String) As Long
Dim lngLenOfChild As Long
lngLenOfChild = Len(strChild)
If lngLenOfChild Then
GetRepeatedTimes = (Len(strParent) - Len(Replace(strParent, strChild, vbNullString))) / lngLenOfChild
End If
End Function
调用演示:
Sub Demo()MsgBox "子字符串 ""56"" 在父字符串 ""1325659568"" 中出现次数为 " & _
CStr(GetRepeatedTimes("1325659568", "56")), vbOKOnly, "演示"
End Sub
温馨提示:答案为网友推荐,仅供参考
第1个回答 推荐于2016-11-12
使用Replace方式依次替换中出现的另一个字符串的字符,比较替换后的长度,再累加差值,就可以计算出总差数,代码如下:
Function Count(mstr, substr)Dim n, c
n = 0
While Len(substr) > 0
c = Left(substr, 1)
substr = Replace(substr, c, "")
n = n + (Len(mstr) - Len(Replace(mstr, c, "")))
Wend
Count = n
End Function
Sub test()
MsgBox Count("13256598", "6135")
End Sub
效果如下:
第2个回答 推荐于2018-03-01
Sub 一串字符在另一串字符出现次数()
Dim a, b, c, x
a = Cells(1, 1)
b = Cells(1, 2)
For i = 1 To Len(b)
x = Replace(a, Mid(b, i, 1), "")
c = c + Len(a) - Len(x)
Next
Cells(1, 3) = c
End Sub 本回答被提问者和网友采纳
Dim a, b, c, x
a = Cells(1, 1)
b = Cells(1, 2)
For i = 1 To Len(b)
x = Replace(a, Mid(b, i, 1), "")
c = c + Len(a) - Len(x)
Next
Cells(1, 3) = c
End Sub
已上传附件