2013-05-20 26 views
0

VBA新手。最後遇到了我無法用公式解決的Excel問題。這是我的示例數據:按關鍵字排列的多行中出現字符的字符數[vba]

----------------------- 
| | A  | B* | 
----------------------- 
| 1 | Text1 | 3001 | 
----------------------- 
| 2 | Text2 | 0231 | 
----------------------- 
| 3 | Text1 | 1003 | 
----------------------- 
| 4 | Text3 | 0012 | 
----------------------- 

我想實現F(A1:A4, 「文本1」,B1:B4, 「3」)= 2

即我要計數的累積對於包含「文本1」的每一行,在列B中出現字符「3」。請注意,列B中的單元格是text和int類型的。如果有一種方法可以在沒有vba的情況下實現這一點,我也會歡迎。

這是我到目前爲止有:

Function CountCharInStr(FilterStr As String, FilterRange As Range, SearchStr As String, StrRange As Range) As Integer 

    Dim Idx As Integer, IsFound As Boolean 
    CountCharInStr = 0 
    IsFound = False 

    For Idx = 1 To FilterRange.Rows.Count 
     IsFound = True 
     If FilterRange(Idx) <> FilterStr Then 
      IsFound = False 
      Exit For 
     End If 

     If IsFound Then 
      CountCharInStr = Len(StrRange(Idx)) - Len(Replace(StrRange(Idx), SearchStr, "")) + CountCharInStr 
      Exit For 
     End If 
    Next Idx 

End Function 

功能目前返回0,初始值,而不是2也想知道是否有一個簡單的方法步驟,通過用戶定義的函數用於調試目的。

非常感謝!

回答

4

您可以直接在工作表中實現這一點:

 =SUM(IF(A1:A4="Text1",LEN(B1:B4)-LEN(SUBSTITUTE(B1:B4,"3","")),0)) 

注意,這是一個數組公式:你必須按Ctrl + Shift +(公式欄)輸入,而不僅僅是輸入時編輯。

如果可能的話,最好避免使用VBA。

讓我知道你是否需要解釋它是如何工作的。

+0

+1很好地完成! –

+0

確實不錯。非常感激! – lajulajay

相關問題