i want to know the times of occurrance one word in the text-box in VB 0.6 - vb6

want to know the count of occurrence one word in the text box in Visual BASIC v.0.6 ?
i tried to use the counter from the list but it was not good
for example: in the following sentence:
" go to play and go to home"... the verb "go" appear 2 times ..then.. i want the code that count the number of occurrence of verb "go" and say to me through label for example: 2 times
for example: in the following sentence:
" go to play and go to home"... the verb "go" appear 2 times ..then.. i want the code that count the number of occurrence of verb "go" and say to me through label for example: 2 times

You can use replace() to remove the word from the string, and then compare the length resulting string with the length of the original string, and devide that by the length of the word
Option Explicit
Private Sub Command1_Click()
Label1.Caption = CStr(CountWord(Text1.Text, "go")) & " times"
End Sub
Private Sub Form_Load()
Text1.Text = " go to play and go to home"
End Sub
Private Function CountWord(strText As String, strWord As String) As Long
CountWord = (Len(strText) - Len(Replace(strText, strWord, ""))) / Len(strWord)
End Function
the function CountWord above finds the amount of strWord in strText, it doesn't search for separate words, but also adds one to the count if strWord is part of a larger word
For example " go to play and go to home to search on google" would count 3 instances of "go"

Try the following code: -
Dim txt$, find$, i1%, count%
txt = "go to play and go to home"
find = "go"
i1 = 0
Do
i1 = InStr(i1 + 1, txt, find)
If i1 > 0 Then
count = count + 1
i1 = i1 + Len(find)
Else
Exit Do
End If
Loop
MsgBox count

You can use regular expressions to count word occurrences
Private Sub Form_Load()
Debug.Print CountWords(" go to play and G.O to home to search on g.o" & vbCrLf & "ogle", "g.o")
End Sub
Private Function CountWords(sText As String, sWord As String) As Long
Dim sPattern As String
sPattern = pvInitRegExp("[-[\]{}()*+?.,\\^$|#\s]").Replace(sWord, "\$&")
CountWords = pvInitRegExp("\s" & sPattern & "\s").Execute(sText).Count
End Function
Private Function pvInitRegExp(sPattern As String) As Object
Set pvInitRegExp = CreateObject("VBScript.RegExp")
With pvInitRegExp
.Pattern = sPattern
.Global = True
.IgnoreCase = True
.MultiLine = True
End With
End Function
This takes care of word boundaries too so "google" is not counted.

Related

How capitalize fullname in vb6

hi all i have this question as bellow
how capitalize full in one vb6 Vb6 string variable
‘example
‘my fullname
Dim fullname as string
Fullname = “abdirahman abdirisaq ali”
Msgbox capitalize(fullname)
it prints abdirahmanAbdirisaq ali that means it skips the middle name space even if I add more spaces its same .
this is my own code and efforts it takes me at least 2 hours and still .
I tired it tired tired please save me thanks more.
Please check my code and help me what is type of mistakes I wrote .
This is my code
Private Function capitalize(txt As String) As String
txt = LTrim(txt)
temp_str = ""
Start_From = 1
spacing = 0
For i = 1 To Len(txt)
If i = 1 Then
temp_str = UCase(Left(txt, i))
Else
Start_From = Start_From + 1
If Mid(txt, i, 1) = " " Then
Start_From = i
spacing = spacing + 1
temp_str = temp_str & UCase(Mid(txt, Start_From + 1, 1))
Start_From = Start_From + 1
Else
temp_str = temp_str & LCase(Mid(txt, Start_From, 1))
End If
End If
Next i
checkName = temp_str
End Function
It's far simpler than that. In VB6 you should use Option Explicit to properly type your variables. That also requires you to declare them.
Option Explicit
Private Function capitalize(txt As String) As String
Dim temp_str as String
Dim Names As Variant
Dim Index As Long
'Remove leading and trailing spaces
temp_str = Trim$(txt)
'Remove any duplicate spaces just to be sure.
Do While Instr(temp_str, " ") > 0
temp_str = Replace(temp_str, " ", " ")
Loop
'Create an array of the individual names, separating them by the space delimiter
Names = Split(temp_str, " ")
'Now put them, back together with capitalisation
temp_str = vbnullstring
For Index = 0 to Ubound(Names)
temp_str = temp_str + Ucase$(Left$(Names(Index),1)) + Mid$(Names(Index),2) + " "
Next
'Remove trailing space
capitalize = Left$(temp_str, Len(temp_str) - 1)
End Function
That's the fairly easy part. If you are only going to handle people's names it still needs more work to handle names like MacFarland, O'Connor, etc.
Business names get more complicated with since they can have a name like "Village on the Lake Apartments" where some words are not capitalized. It's a legal business name so the capitalization is important.
Professional and business suffixes can also be problematic if everything is in lower case - like phd should be PhD, llc should be LLC, and iii, as in John Smith III, would come out Iii.
There is also a VB6 function that will capitalize the first letter of each word. It is StrConv(string,vbProperCase) but it also sets everything that is not the first letter to lower case. So PhD becomes Phd and III becomes Iii. Where as the above code does not change the trailing portion to lower case so if it is entered correctly it remains correct.
Try this
Option Explicit
Private Sub Form_Load()
MsgBox capitalize("abdirahman abdirisaq ali")
MsgBox capitalize("abdirahman abdirisaq ali")
End Sub
Private Function capitalize(txt As String) As String
Dim Names() As String
Dim NewNames() As String
Dim i As Integer
Dim j As Integer
Names = Split(txt, " ")
j = 0
For i = 0 To UBound(Names)
If Names(i) <> "" Then
Mid(Names(i), 1, 1) = UCase(Left(Names(i), 1))
ReDim Preserve NewNames(j)
NewNames(j) = Names(i)
j = j + 1
End If
Next
capitalize = Join(NewNames, " ")
End Function
Use the VB6 statement
Names = StrConv(Names, vbProperCase)
it's all you need (use your own variable instead of Names)

How to speed up this code to find and delete rows if a substring is found

Below code works great as expected the only downside is its slow because I am using this to search for all the instances of the substring and delete the Entire row if found in any cell of the whole workbook.
Aim is simple just delete the entirerow if the entered string is found in any cell string
Dim wo As Worksheet, ws As Worksheet
Dim I As Long, j As Long, m As Long
Dim toFind As String, testStr As String
Dim pos As Long
Dim lstRow As Long, cutRow As Long
Dim WS_Count As Integer
Dim Cell As Range
Option Compare Text
Option Explicit
Sub SearchDelete()
toFind = InputBox("Enter the substring you want to search for.", "Welcome", "AAAA")
toFind = Trim(toFind)
j = 0
If toFind = "" Then
MsgBox "Empty String Entered.Exiting Sub Now."
Exit Sub
Else
WS_Count = ActiveWorkbook.Worksheets.Count
'Begin the loop.
For I = 1 To WS_Count
Label1:
For Each Cell In Worksheets(I).UsedRange.Cells
If Trim(Cell.Text) <> "" Then
pos = 0
pos = InStr(1, Trim(Cell.Text), toFind, vbTextCompare)
If pos > 0 Then 'match Found'
cutRow = Cell.Row
Worksheets(I).Rows(cutRow).EntireRow.Delete
j = j + 1
GoTo Label1
Else: End If
Else: End If
Next Cell
Next I
End If
MsgBox "Total " & j & " Rows were deleted!"
End Sub
Individual operations are pretty much always slower than bulk operations and the Range.Delete method is no exception. Collecting the matching rows with a Union method and then performing the removal en masse will significantly speed up the operation.
Temporarily suspending certain application environment handlers will also help things along. You do not need Application.ScreenUpdating active while you are removing rows; only after you have completed the operation.
Option Explicit
Option Compare Text
Sub searchDelete()
Dim n As Long, w As Long
Dim toFind As String, addr As String
Dim fnd As Range, rng As Range
toFind = InputBox("Enter the substring you want to search for.", "Welcome", "AAAA")
toFind = Trim(toFind)
If Not CBool(Len(toFind)) Then
MsgBox "Empty String Entered.Exiting Sub Now."
GoTo bm_Safe_Exit
End If
'appTGGL bTGGL:=False 'uncomment this line when you have finsihed debugging
With ActiveWorkbook
For w = 1 To .Worksheets.Count
With .Worksheets(w)
Set fnd = .Cells.Find(what:=toFind, lookat:=xlPart, _
after:=.Cells.SpecialCells(xlCellTypeLastCell))
If Not fnd Is Nothing Then
Set rng = .Rows(fnd.Row)
n = n + 1
addr = fnd.Address
Do
If Intersect(fnd, rng) Is Nothing Then
n = n + 1
Set rng = Union(rng, .Rows(fnd.Row))
End If
Set fnd = .Cells.FindNext(after:=fnd)
Loop Until addr = fnd.Address
Debug.Print rng.Address(0, 0)
rng.Rows.EntireRow.Delete
End If
End With
Next w
End With
Debug.Print "Total " & n & " rows were deleted!"
bm_Safe_Exit:
appTGGL
End Sub
Public Sub appTGGL(Optional bTGGL As Boolean = True)
Application.ScreenUpdating = bTGGL
Application.EnableEvents = bTGGL
Application.DisplayAlerts = bTGGL
Application.Calculation = IIf(bTGGL, xlCalculationAutomatic, xlCalculationManual)
Debug.Print Timer
End Sub
The answer to your question: "How to speed up this code to find and delete rows if a substring is found" is - DON'T repeat the search from the top of the sheet after you found and removed the row!

Creating a userform that prints textbox input to specific spots in the document

I was working on a system in VBA word. The goal of the system is to replace several different words in a document with input from a text box. So far I have a userform with 12 different text boxes each containing input from a user to replace words in the document. I made a button in the userform to print all the input from the textboxes to the document.
For each textbox I made the following code:
Sub FindAndReplaceAllStoriesHopefully()
Dim myStoryRange As Range
'
'
'Loop replaces everything with <KLANTNAAM> in the document
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.Find
.Text = "<KLANTNAAM>"
.Replacement.Text = TextBox1.Value
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
Do While Not (myStoryRange.NextStoryRange Is Nothing)
Set myStoryRange = myStoryRange.NextStoryRange
With myStoryRange.Find
.Text = "<KLANTNAAM>"
.Replacement.Text = TextBox1.Value
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
Loop
Next myStoryRange
So far I did this for all 12 textboxes and it works but it isn't smooth. The
button upon getting clicked is calling the function with
Call FindAndReplaceAllStoriesHopefully
I have a few problems which I just cannot fix:
Once the button is clicked and some textboxes are not filled by the user, the marked words like <KLANTNAAM> are still replaced and removed from the document.
The performance of the macro is not great since the same code is copied 12 times.
Once the button is clicked, there is no easy way for the user to undo mistakes typed in the userform since the results are already printed.
I was hoping to get some tips so I can finalize this application.
Something like this:
Private Sub CommandButton1_Click()
Dim numBlank As Long, n As Long, txt As String
Dim bookMarkName As String
numBlank = Me.CountBlanks
If numBlank > 0 Then
If MsgBox(numBlank & " entries are blank!. Continue?", _
vbExclamation + vbOKCancel) <> vbOK Then
Exit Sub
End If
End If
For n = 1 To 4
txt = Me.Controls("Textbox" & n).Text
bookMarkName = "BOOKMARK" & n
FindAndReplaceAllStoriesHopefully bookMarkName, txt
Next n
End Sub
Function CountBlanks() As Long
Dim n As Long, b As Long
b = 0
For n = 1 To 4
If Len(Me.Controls("Textbox" & n).Text) = 0 Then
b = b + 1
End If
Next n
CountBlanks = n
End Function

How to display length of word count in vb?

So I've been trying for hours to figure out how to display the length of word count in vb.
For example, if I type in a sentence in a rich textbox and I click a button, I want a form to show up listing the number of one-letter words, two-letter words, three-letter words and so on within that sentence. The number of words of specific length will be outputted in labels, of course.
I found this short code online for word count:
dim wordcount as integer
dim a as string() = RichText.Text.Split(" ")
wordcount = a.length
However, I'm not sure if this code can be used to get the length of word count. Any ideas of how I can achieve outputting the number of words of a specific length in a label? Thank you.
What about something like:
Private Sub mnuCount_Click()
Const DELIMITERS As String = vbNewLine & " !"",.:;?"
Dim WordCounts(1 To 100) As Long
Dim Msg As String
Dim I As Integer
Dim WordCount As Long
With RTB
.Visible = False
.SelStart = 0
Do
.UpTo DELIMITERS, vNegate:=True
.Span DELIMITERS, vNegate:=True
If .SelLength > 0 Then
WordCounts(.SelLength) = WordCounts(.SelLength) + 1
.SelStart = .SelStart + .SelLength
Else
Exit Do
End If
Loop
.SelStart = 0
.Visible = True
End With
Msg = "Length" & vbTab & "Count"
For I = 1 To 100
If WordCounts(I) > 0 Then
Msg = Msg & vbNewLine _
& CStr(I) & vbTab & CStr(WordCounts(I))
WordCount = WordCount + WordCounts(I)
End If
Next
Msg = Msg & vbNewLine _
& "Grand total:" & vbNewLine _
& vbTab & CStr(WordCount)
MsgBox Msg
End Sub
Pradnya's code, translated to VB6:
Option Explicit
Private Sub Command1_Click()
Dim str As String
Dim splitStr() As String
Dim i As Integer
str = "ABC DEF GHIJ KLMNOPQ"
splitStr = Split(str, " ")
MsgBox "Number of words = " & UBound(splitStr) + 1 & vbCrLf & _
"Average Length = " & Len(Replace(str, " ", "")) / (UBound(splitStr) + 1)
End Sub
I made a few simplifications as well. There's no need to go through the loop to get the average. All you have to do to get the length of the whole is remove the spaces and divide by the number of elements in the array.
However, if you want to get a count of the number of words of each length, you'll have to loop through the array, getting the length of each word and storing those values one by one. Best way to do that is to set a reference to scrrun.dll (Windows Scripting Runtime) and use a Dictionary object to store the values.

vb6 split space delimited string at every nth space

I have a space delimited string variable. I would like to store the contents of the variable into an array. Using split, I can store every space delimited value in an array. I would prefer if I could separate the string variable at every 7th space. For example, the text could read:
"hello hello hello hello hello hello hello hi hi hi hi hi hi hi hey hey hey hey hey hey hey"
This isn't the actual content of the string, but a simpler version that is easier to read. I want to separate at the places where the words change, or every 7th space. Any help would be greatly appreciated. My current code looks like this, which splits at every space.
ReDim StatsArray(ArrInc)
StatsArray = Split(Stats)
For i = 0 To UBound(StatsArray())
If i > UBound(StatsArray()) Then
ReDim Preserve StatsArray(i + ArrInc)
End If
' MsgBox StatsArray(i) ' When not commented out, this help me check the array
Next
There isn't any built-in function that will do this for you. A couple of solutions come to mind: (1) Do your split, then iterate your array. Concatenate seven array elements in a string variable. Write the result to a new array. Rinse and repeat. (2) Create an Array. Iterate through the string character by character, pushing each character into a variable and keeping track of the spaces you encounter; when you reach the seventh space add an element to your array, copy the variable to it, and clear the variable. Rinse and repeat.
The first one strikes me as a bit faster, but I could be quite wrong about that.
If I understand what you're trying to do, a string of "1234 12345678 123" would get split into 1234, 1234567, 8, 123. Is this correct?
If so, then you can use Regular Expressions to do the split for you.
Function Split7(S As String)
Dim regex As New RegExp
regex.Pattern = "[^ ]{7}"
regex.Global = True
Split7 = Split(regex.Replace(S, "$& "), " ")
End Function
This will insert a space after every 7th character that is not a space. Then use the split function to get the whole thing into an array.
Another stab at it, though I'd probably optimize the ReDim Preserves, doing them in chunks:
Option Explicit
Private Function SplitN( _
ByRef Source As String, _
ByVal Delim As String, _
ByVal N As Long) As String()
'Delim can be multi-character.
'Always returns at least 1-element result,
'even if Source = "".
Dim SearchPos As Long
Dim PartPos As Long
Dim DelimPos As Long
Dim Parts() As String
Dim DelimCount As Long
Dim PartsCount As Long
SearchPos = 1
PartPos = SearchPos
Do
DelimPos = InStr(SearchPos, Source, Delim)
If DelimPos > 0 Then
DelimCount = DelimCount + 1
If DelimCount = N Then
DelimCount = 0
ReDim Preserve Parts(PartsCount)
Parts(PartsCount) = _
Mid$(Source, PartPos, DelimPos - PartPos)
PartsCount = PartsCount + 1
PartPos = DelimPos + Len(Delim)
End If
SearchPos = DelimPos + Len(Delim)
End If
Loop While DelimPos > 0
ReDim Preserve Parts(PartsCount)
Parts(PartsCount) = Mid$(Source, PartPos)
SplitN = Parts
End Function
Private Sub Form_Load()
Dim S As String
Dim Parts() As String
Dim P As Long
S = "hello hello hello hello hello hello hello " _
& "hi hi hi hi hi hi hi " _
& "hey hey hey hey hey hey hey"
Text1.SelStart = 0
Text1.SelText = S & vbNewLine & vbNewLine
Parts = SplitN(S, " ", 7)
Text1.SelText = "Ubound() = " & UBound(Parts) & vbNewLine
For P = 0 To UBound(Parts)
Text1.SelText = Parts(P) & vbNewLine
Next
End Sub

Resources