2013-10-15 49 views
0

我想從給定的字符串/句子中統計某個單詞的出現次數。我已經嘗試使用下面的代碼,但它不起作用。計數在VBA中一個句子中出現一個單詞

Sub main() 
    MainStr = " yes no yes yes no yes no " 
    Str1 = " yes " 
    MsgBox UBound(Split(MainStr, Str1)) 
End Sub 

在上面的代碼中,我想從MainStr中搜索Str1。在大多數博客中,人們給出了使用「拆分」功能來計算事件發生的解決方案。但是,當搜索詞緊接在一起時,它不會給出正確的結果。

在上面的情況下,搜索詞是「是」&它將在第3位&第4位。

時, MainStr =「是否是否是否是」 STR1 =「是」

請幫我這正如我已經試過/搜索上面的代碼會給出正確的結果,下面的場景很多找到解決方案。

謝謝!

+0

你可以指望使用InStr函數發生。 –

+0

Mike,我不想運行一個循環來計算事件的發生。我正在爲此尋找一個非常Compaq的代碼。你能不能讓我知道如何使用instr來實現這一點。 –

+0

您需要在循環中使用它。 –

回答

0
I beleive you will need a loop, Not sure you can accomplish this with just 1 line of code, maybe I am wrong 


Dim s As String 
Dim searchWord As String 
Dim iSearchIndex As Integer 
Dim iCounter 
searchWord = "YES" 
s = "yes no yes yes no no yes yes yes no yes" 
Do While True 
    'get the location of the search word 
    iSearchIndex = InStr(1, UCase(s), "YES") 
    'check to make sure it was found 
    If iSearchIndex > 0 Then 
     'create a string removing the found word 
     s = Mid(s, iSearchIndex + Len(searchWord)) 
     'add 1 to our counter for a found word 
     iCounter = iCounter + 1 
    Else 
     Exit Do 'nothing found so exit 
    End If 
Loop 
MsgBox CStr(iCounter) 
3

可以嘗試:

HowManyOccurrences = ubound(split(whole_string, search_string)) 

其將使用search_string的作爲分隔符到和陣列返回的數組中元素的數目whole_string。

你將不得不遍歷那麼最有可能(或拿出一個遞歸的正則表達式,然後計算捕獲或東西):

Dim whole_string As String 
Dim search_string As String 
Dim temp As String 
Dim ctr As Integer 

whole_string = "yes no yes yes no yes no " 
search_string = "yes" 
temp = whole_string 
ctr = 0 

While (InStr(1, temp, search_string) > 0) 
    temp = Replace(temp, search_string, "", 1, 1) 
    ctr = ctr + 1 
Wend 

MsgBox (ctr) 
+0

+1爲巧妙 –

+0

嘗試用我提供的字符串。這不會有效。用我給出的MainStr&Str1值進行測試。 –

+0

邁克,以上方法將不適用於情況時whole_string =「是否昨天是否是否」 search_string =「是」 –

相關問題