vb6搜索文本框指定内容,显示包涵关键词的总数

2024-11-20 13:21:04
推荐回答(5个)
回答(1):

Private Sub Command1_Click()
Text1 = "AAAAAbCCCCbssssbjjjjjb"
s = "b"
MsgBox "一共" & SearchCount(Text1, s) & "个" & s
End Sub

Function SearchCount(ss, s) As Integer
p = InStr(1, ss, s, vbTextCompare)
Do While p > 0
SearchCount = SearchCount + 1
p = InStr(p + Len(s), ss, s, vbTextCompare)
Loop
End Function
'如果区分大小写,去掉参数vbTextCompare
'Text1中包含2个AA,如果将Len(s)修改为1,将包含4个AA

整合到一个过程中,即不使用函数:
Private Sub Command2_Click()
Dim i As Integer
Text1 = "AAAAAbCCCCbssssbjjjjjb"
s = "b"
p = InStr(1, Text1, s, vbTextCompare)
Do While p > 0
i = i + 1
p = InStr(p + Len(s), Text1, s, vbTextCompare)
Loop
MsgBox "一共" & i & "个" & s
End Sub

回答(2):

超另类+实用+简单思维:
Private Sub Command1_Click() 'Command1是搜索按钮,点击后即搜索text1
MsgBox "一共" & UBound(Split(Text1, "b")) & "个b"
End Sub

回答(3):

'text1存放字符串,text2存放搜索的内容,1个Check1区分大小写

Private Sub Form_Load()
Check1.Caption = "区分大小写"
Text1.Text = "AAAAAbCCCCbssssbjjjjjb"
Text2.Text = "b"
End Sub
Private Sub Command1_Click()
Dim n As Integer
n = Len(Text1.Text) - Len(Replace(Text1.Text, Text2.Text, "", , , IIf(Check1.Value = 1, vbBinaryCompare, vbTextCompare)))
MsgBox Text1.Text & "中共有" & n & "个" & Text2.Text
End Sub

回答(4):

Private Sub Command1_Click()
Dim i As Integer, j As Integer, c As Integer
Dim s As String

c = 0
s = Text1.Text
i = InStr(s, Text2.Text) '查找是否存在指定字符
s = Mid(s, i + 1) '去除已经匹配过的字符
Do Until i = 0
c = c + 1 '统计个数
i = InStr(s, Text2.Text)
s = Mid(s, i + 1)
Loop
MsgBox c
End Sub

希望回答对你有帮助

回答(5):

另类思维:

Private Sub Form_Load()
Const Str = "AAAAAbCCCCbssssbjjjjjb"

Const SubString = "b"

MsgBox "共" + StrCount(Str, SubString) + "个" + SubString + "字符!"
End Sub

Private Function StrCount(Str, SubString As String) As String
Dim a As Variant

If Trim(Str) = "" Or Trim(SubString) = "" Then
StrCount = ""
Else
a = Split(Str, SubString)

StrCount = UBound(a) - 1
End If
End Function