字符串在VBA中包含char的次数

时间:2013-12-24 22:50:07

标签: string vba

有没有办法知道字符串包含特定字符的次数?

e.g。字符串“string”包含逗号的次数。

    Dim strin as strin
    strin = "qwe, asd, zcx"

2 个答案:

答案 0 :(得分:4)

旧的“技巧”是用其他东西替换字符串,并在替换之前和之后检查字符串长度的差异。

Dim replaced as string
replaced = Replace(strin, ",", "")
' count = Len(string) - Len(replaced)

如果必须计算多字符字符串,例如逗号和空格,则必须将结果除以要替换的字符串的长度:

Dim replaced as string
replaced = Replace(strin, ", ", "")
' count = (Len(string) - Len(replaced)) / 2

答案 1 :(得分:1)

我认为最好的方法是使用函数。

下面的代码可以解决问题。

sub TestCharCountFunction ' this sub is for testing the function

strin = "qwe, asd, zcx"

   msgbox  "Character appears " & charcounter( strin, "," ) & " time(s)"

end sub

function CharCounter (byval MyString as string, byval CharToSearch as string) as integer


dim X as integer

charcounter = 0

for X= 1 to len(mystring)

    if mid(mystring, x,1) = chartosearch then charcounter = charcounter + 1

next

end function