Can somebody help me fix this code, I have two textbox where when you paste the text on the 1st Textbox and click the search button, it highlighted the exact text on the 2nd textbox if it is present on the 2nd textbox. But when the string on 2nd textbox contains linefeed/newline, it added one character from the start of the text. Here is the code:
Private Sub FindText(ByVal start_at As Integer)
Dim pos As Integer
Dim target As String
target = Textbox1.Text
pos = InStr(start_at, Textbox2.Text, target)
If pos > 0 Then
' We found it.
TargetPosition = pos
Textbox2.SelStart = TargetPosition - 1
Textbox2.SelLength = Len(target)
Textbox2.SetFocus
Else
' We did not find it.
MsgBox "Not found."
Textbox2.SetFocus
End If
End Sub
' Search button
Private Sub cmdSearch_Click()
FindText 1
End Sub
I believe the problem is that Textbox is treating newline as a single character while Len() counts as CRLF as two. You should probably count the number of times CRLF appears in the text preceding the match target and adjust SelStart accordingly. Try this line instead:
Textbox2.SelStart = Len(Replace(Left(target, pos - 1), vbCrLf, "^")) - 1
'Textbox2.SelLength = Len(Replace(target, vbCrLf, "^"))
If target can include line breaks you may have a similar problem with SelLength which is why I've left the second, commented line. This works by substituting two-character line-break sequences into a single-character string. It's completely arbitrary what value to use for replacement since the result is discarded and only the length ultimately matters.
Related
I am wanting to make a wildcard search character (ex. Binary%) so when they click search it finds all the files with the word Binary in the filename and loads them into a list box. My current code is below.
Private Sub _test_TextChanged(sender As Object, e As TextChangedEventArgs) Handles _test.TextChanged
For x As Integer = 0 To _listbox.Items.Count - 1
If _listbox.Items(x).ToString = _test.Text$ Then
_listbox.SelectedIndex = x
Return
End If
Next
End Sub
Any help is welcome!
Thank you!
-Kyvex
What you are asking doesn't really match your code.
... "when they click search it finds all the files" ...
But you have a TextChanged event handler of a TextBox (not a Button)
..."with the word Binary in the filename and loads them into a list box"
But you select only the first item which matches the filter of items already in a ListBox
To get your code to do what it seems to want to do, simply use the Like operator and add the wildcard character (*) after the TextBox.Text
For x As Integer = 0 To _listBox.Items.Count - 1
If _listBox.Items(x).ToString Like _test.Text & "*" Then
_listBox.SelectedIndex = x
Return
End If
Next
Now you can select the first item in the listbox which matches the filter
If you have a multi-select ListBox, you can use this
If _test.Text = "" Then Exit Sub
_listBox.SelectionMode = SelectionMode.MultiSimple
For x As Integer = 0 To _listBox.Items.Count - 1
_listBox.SetSelected(x, _listBox.Items(x).ToString Like _test.Text & "*")
Next
(the filter logic is the same as the first example)
And you can make it case-insensitive
_listBox.SetSelected(x, _listBox.Items(x).ToString().ToUpper() Like _test.Text.ToUpper() & "*")
I have been using this code to Bold-Underline all the headers in my word doc:
Sub Underline_Headers()
Dim p As Paragraph
For Each p In ActiveDocument.Paragraphs
If Len(p.Range.Text) < 70 Then
p.Range.Font.Underline = True
p.Range.Font.Bold = True
End If
Next p
End Sub
This works great - as long as every header is less than 70 characters long, and the paragraph underneath it is 70 or more characters.
But many times the header can be longer than 70 characters, and the paragraph under the header can be less than 70 characters.
However, the headers always never end with any punctuation, like a "." but the paragraphs underneath them always do.
I am trying to fix the code above to look for all paragraphs not ending in a "." and then Bold-Underline them. In other words, I want to change the rule.
I tried the only thing that made sense to me. The code did not break, but it ended up bold-underline the entire document:
Sub Underline_Headers()
Dim p As Paragraph
For Each p In ActiveDocument.Paragraphs
If Right(p.Range.Text,1) <> "." Then
p.Range.Font.Underline = True
p.Range.Font.Bold = True
End If
Next p
End Sub
This supposedly looks for all paragraphs where the last character is not ".", which if that worked, would isolate all the headers and only bold-underline them, but obviously that doesn't work.
The last character in every paragraph is a carriage return, Chr(13). The text ends one character before that. The code below also considers the possibility that someone ended a paragraph's text with one or more blank spaces. It takes the "cleaned" string and looks for the last character in a string of possible exceptions, like .?!. You can reduce this string to a single full stop or extend it to include more cnadidates for exception.
Private Sub UnderlineTitles()
Dim Para As Paragraph
Dim Txt As String
Application.ScreenUpdating = False
For Each Para In ActiveDocument.Paragraphs
Txt = Para.Range.Text
Txt = RTrim(Left(Txt, Len(Txt) - 1))
' you can extend the list to include characters like ")]}"
If InStr(".?!", Right(Txt, 1)) = 0 Then
' to choose a different style of underline, remove
' "= wdUnderlineSingle", type "=" and select from the dropdown
Para.Range.Font.Underline = wdUnderlineSingle
End If
Next Para
Application.ScreenUpdating = True
End Sub
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a TextBox that includes more words
Example:
I'm pRoFeSSoinaL coder
I want to search for the word pRoFeSSoinaL (that contains uppercase and lowercase letters) and then replace it.
OK let me try and address your problem again based on your image:
And on your comment:
...but i need search about word have More than a change of letters example (execute, ExEcute, eXecute, execUtE........ETC) i need find word No matter how large and small the letters are see this proof
Again, if I have this right, you would like to find all occurrences of a word regardless of it's case. In effect you would like for your application to work a bit like Notepad.
I've put together some code that will use the following methods:
String.ToLower:
Returns a copy of this string converted to lowercase.
TextBox.Select:
Selects a range of text in the text box.
String.Remove:
Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.
String.Insert:
Returns a new string in which a specified string is inserted at a specified index position in this instance.
String.Substring:
Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.
I have three Button controls that I've put a bit a code behind. One will find the next occurrence of a word, another will replace the next occurrence of a word and the last one will replace all occurrences of a word.
Now it's not my job to design your application but for ease I have also popped on three TextBox controls. This is how my form looks:
To find the next occurrence of professional this is the code I used:
Private Sub btnFindNext_Click(sender As Object, e As EventArgs) Handles btnFindNext.Click
'check word exists
If txtTextToSearch.Text.ToLower().Contains(txtWordToFind.Text.ToLower()) Then
'reset position if at end of text
If txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1) < 0 Then
position = 0
End If
'set position of next occurrence
position = txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1)
'select next occurrence
txtTextToSearch.Select(position, txtWordToFind.Text.Length)
End If
End Sub
This is a screenshot of how it would look when you click the button:
Clicking the button again will select the next occurrence of the word. It will keep toggling between the two in my example.
To replace the next occurrence of professional this is the code I used:
Private Sub btnReplaceNext_Click(sender As Object, e As EventArgs) Handles btnReplaceNext.Click
'check word exists
If txtTextToSearch.Text.ToLower().Contains(txtWordToFind.Text.ToLower()) Then
'reset position if at end of text
If txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1) < 0 Then
position = 0
End If
'set position of next occurrence
position = txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1)
'remove old word
txtTextToSearch.Text = txtTextToSearch.Text.Remove(position, txtWordToFind.Text.Length())
'insert new word
txtTextToSearch.Text = txtTextToSearch.Text.Insert(position, txtReplaceWith.Text)
End If
End Sub
This is a screenshot of how it would look when you click the button:
Clicking the button again will replace the next occurrence of the word.
To replace all occurrences of the word professional this is the code I used:
Private Sub btnReplaceAll_Click(sender As Object, e As EventArgs) Handles btnReplaceAll.Click
'check word exists
If txtTextToSearch.Text.ToLower().Contains(txtWordToFind.Text.ToLower()) Then
'reset position if at end of text
If txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1) < 0 Then
position = 0
End If
'set position of next occurrence
position = txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1)
While position > 0 AndAlso position < txtTextToSearch.Text.Length
'remove old word
txtTextToSearch.Text = txtTextToSearch.Text.Remove(position, txtWordToFind.Text.Length())
'insert new word
txtTextToSearch.Text = txtTextToSearch.Text.Insert(position, txtReplaceWith.Text)
'set position of next occurrence
position = txtTextToSearch.Text.ToLower().IndexOf(txtWordToFind.Text.ToLower(), position + 1)
End While
End If
End Sub
This is a screenshot of how it would look when you click the button:
My code will need adapting I'm sure but it should give you something to go on. As for the level of detail I have gone to, may not benefit you but may benefit others that visit this question. Hope this helps.
Judging from your screenshot (http://i.imgur.com/77wdZoI.png) you appear to be after case-insensitive string matching.
The simplest way is to use the String.IndexOf(String, StringComparison) overload to perform case-insensitive comparison:
Private Function FindText(ByVal Source As String, ByVal Text As String) As Integer
Return Source.IndexOf(Text, StringComparison.OrdinalIgnoreCase)
End Function
Usage example:
Dim TextToFind As String = "professional"
Dim TextPos As Integer = FindText(TextBox1.Text, TextToFind)
If TextPos > -1 Then 'Match found.
TextBox1.SelectionStart = TextPos
TextBox1.SelectionLength = TextToFind.Length
End If
I am writing a simple hangman program and I want to replace something in my variable which stores the letters of the word that have been found.
Here is the code:
Replace(wordLettersFound, Mid(wordLettersFound, counter, 1), letter)
wordLettersFound, counter and letter are 3 of the variables I am using.
The variable is all underscores before this script, but it does not change! Can anyone help me with this?
P.S.
I do not know what version of VB I am using, visual studio community 2015 just says 'visual basic'.
Replace doesn't modify the string but returns a new string with the replacement so you should assign it to the variable:
wordLettersFound = Replace(wordLettersFound, Mid(wordLettersFound, counter, 1), letter)
Another way to do replace,
Dim theLetters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzAAA"
theLetters = theLetters.Replace("A"c, "#"c)
There is another way to replace a character in a string. Using the Replace function is a bit awkward in your case because, at the start, all the characters are underscores - Replace as you're using it will replace all of them with the found character.
Instead, you can cut up the string to the piece to the left of the desired replacement, add in the replacement character, and add on the rest of the string. That line is the one after the comment "chop foundWord up and put the character in the right place" in this code:
Module Module1
Sub Main()
Dim wordToFind = "alphabet"
' make a string of dashes the same length as the word to find
Dim foundWord = New String("-"c, wordToFind.Length)
While foundWord <> wordToFind
Console.Write("Enter your guess for a letter: ")
Dim guess = Console.ReadLine()
' make sure the user has only entered one character
If guess.Length = 1 Then
' see if the letter is in the string
Dim pos = wordToFind.IndexOf(guess)
While pos >= 0
' chop foundWord up and put the character in the right place
foundWord = foundWord.Substring(0, pos) & guess & foundWord.Substring(pos + 1)
' see if there are any more of the same letter
pos = wordToFind.IndexOf(guess, pos + 1)
End While
' show the user the current progress
Console.WriteLine(foundWord)
Else
Console.WriteLine("Please enter just one letter!")
End If
End While
Console.WriteLine("You did it!")
Console.WriteLine("Press enter to leave the program.")
Console.ReadLine()
End Sub
End Module
N.B. Do not use all that code directly for homework because your teacher will find this. And that goes to anyone else doing homework - you know who you are ;)
please try to specifically answer my question and not offer alternative approaches as I have a very specific problem that needs this ad-hoc solution. Thank you very much.
Automatically my code opens Word through VB.NET, opens the document, finds the table, goes to a cell, moves that cells.range.text into a String variable and in a For loop compares character at position p to a String.
I have tried Strings:
"^p", "^013", "U+00B6"
My code:
Dim nextString As String
'For each cell, extract the cell's text.
For p = 17 To word_Rng.Cells.Count
nextString = word_Rng.Cells(p).Range.Text
'For each text, search for structure.
For q = 0 To nextString.Length - 1
If (nextString.Substring(q, 1) = "U+00B6") Then
Exit For
End If
Next
Next
Is the structural data lost when assigning the cells text to a String variable. I have searched for formatting marks like this in VBA successfully in the past.
Assuming that your string contains the character, you can use ChrW to create the appropriate character from the hex value, and check for that:
If nextString.Substring(q, 1) = ChrW(&h00B6) Then
Exit For
End If
UPDATE
Here's a complete example:
Dim nextString = "This is a test " & ChrW(&H00B6) & " for that char"
Console.WriteLine(nextString)
For q = 0 To nextString.Length - 1
If nextString(q) = ChrW(&H00B6) Then
Console.WriteLine("Found it: {0}", q)
End If
Next
This outputs:
This is a test ΒΆ for that char
Found it: 15