I'm trying to use this script to compare a users input from a text box with the 22 correct words. I'm not looking for multiple cases, such as VICE is in ADVICE so it would be 2 values; I want it to have the string values to accept only equal values.
At the moment, it is only recognizing the first word TIED and displays a message box "found", but it doesn't not recognize any other word in the list.
I am writing in visual basic script
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim StrCorrect() As String = {"TIED", "VICE", "ICED", "DIVE", "DIET", "DATE", "CITE", "CAVE", "AIDE", "ACED", "CITED", "ACTED", "VACATE", "CATTIE", "ADVICE", "AVIATE", "ACTIVE", "VACATED", "DICTATE", "AVIATED", "ACTIVATE", "ACTIVATED"}
Dim Find As String = userinput
For Each Str As String In StrCorrect
If StrComp(Str, userinput, CompareMethod.Text).ToString = 0 Then
MsgBox("Found" & userinput)
Return
Else : MsgBox("incorrect word")
Return
End If
Next
End Sub
The problem is that your loop is explicitly returning if the first item isn't a match. You only know you don't have a match if your loop completes without finding one, so try something like this instead:
For Each Str As String In StrCorrect
If StrComp(Str, userinput, CompareMethod.Text).ToString = 0 Then
MsgBox("Found" & userinput)
Return
End If
Next
MsgBox("incorrect word")
This will only display "incorrect word" if all of the items in your list fail the first test.
Why STRCOMP? Why not a direct comparision if you want an exact match?
For Each Str As String In StrCorrect
If Str = Find Then
MessageBox.Show("Found :" & Str)
End If
Next
Try like below, It will help you...
Sample :
Dim result As String() = Array.FindAll(StrCorrect, Function(s) s.Equals(Find))
If (result.Length > 0) Then
MsgBox("Found : " & userinput)
Else
MsgBox("incorrect word")
End If
Full Code :
Dim StrCorrect() As String = {"TIED", "VICE", "ICED", "DIVE", "DIET", "DATE", "CITE", "CAVE", "AIDE", "ACED", "CITED", "ACTED", "VACATE", "CATTIE", "ADVICE", "AVIATE", "ACTIVE", "VACATED", "DICTATE", "AVIATED", "ACTIVATE", "ACTIVATED"}
Dim Find As String = userinput
Dim result As String() = Array.FindAll(StrCorrect, Function(s) s.Equals(Find))
If (result.Length > 0) Then
MsgBox("Found : " & userinput)
Else
MsgBox("incorrect word")
End If
I would use a for loop, something like
For i As Integer = 0 To StrCorrect.Length - 1
If StrCorrect(i) = Find Then
MsgBox("Found" & Find)
Return
'End if
'The else statement simply alerting that it didnt find the right word on this iteration
'The else can be removed if you dont want this alert
Else
MsgBox("incorrect word")
'Return
End If
Next
Related
I have a string filled with the contents of a textbox (pretty large).
I want to search through it and display all occurances of this word. In addition I need the searchresult to display some charachters in the string before and after the actual searchterm to get the context for the word.
The code below is part of a code that takes keywords from a listbox one by one using For Each. The code displays the first occurance of a word together with the characters in front and after the word - and stop there. It will also display "no Match for: searched word" if not found.
As stated in the subject of this question - I need it to search the whole string and display all matches for a particular word together with the surrounding characters.
Where = InStr(txtScrape.Text, Search)
If Where <> 0 Then
txtScrape.Focus()
txtScrape.SelectionStart = Where - 10
txtScrape.SelectionLength = Where + 50
Result = txtScrape.SelectedText
AllResults = AllResults + Result
Else
AllResults = AllResults + "No Match for: " & item
End If
I recommend that you can split the string into long sentences by special symbols, such as , : ? .
Split(Char[])
You can refer to the following code.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox1.Text = ""
Dim Index As Integer
Dim longStr() As String
Dim str = TextBox3.Text
longStr = TextBox1.Text.Split(New Char() {CChar(":"), CChar(","), CChar("."), CChar("?"), CChar("!")})
Index = 0
For Each TheStr In longStr
If TheStr.Contains(str) Then
RichTextBox1.AppendText(longStr(Index) & vbCrLf)
End If
Index = Index + 1
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "....."
End Sub
End Class
Result:
Try like this:
Dim ArrStr() As String
Dim Index As Integer
Dim TheStr As String
Dim MatchFound As Boolean
MatchFound = False
ArrStr = Split(txtScrape.text," ")
Index = 1
For Each TheStr In ArrStr
If TheStr = Search Then
Console.WriteLine(Index)
MatchFound = True
End If
Index = Index + 1
Next
Console.WriteLine(MatchFound)
Inside the If statement you will get the index there. And MatchFound is the Boolean value if match found.
I have created the code to search through each string within a listbox to get a substring up until the first space (this is the ID) and check whether the typed ID is in use.
I want to edit this code to skip checking the selected item within the listbox.
For Each lstitem As String In Form1.lst_input.Items
Dim num As Integer = 0
For Each ch As Char In lstitem
If Not Char.IsDigit(ch) Then
Exit For
Else : num += 1
End If
Next ch
If lstitem.Substring(0, Val(num)) = txt_id.Text Then
MsgBox("ID is currently in use", MsgBoxStyle.OkOnly, "ID in use")
txt_id.Text = ""
txt_id.Focus()
Exit Sub
End If
I have tried:
For Each lstitem As String In Form1.lst_input.Items(Not Form1.lst_input.SelectedItem)
and
If lstitem Is Form1.lst_input.SelectedItem Then
but neither work.
Can anyone help?
I finially figured it out. I used the following code:
For Each lstitem As String In Form1.lst_input.Items
Dim num As Integer = 0
If Not lstitem = Form1.lst_input.Items(Form1.lst_input.SelectedIndex) Then
For Each ch As Char In lstitem
If Not Char.IsDigit(ch) Then
Exit For
Else : num += 1
End If
Next ch
End If
If lstitem.Substring(0, Val(num)) = txt_id.Text Then
MsgBox("ID is currently in use", MsgBoxStyle.OkOnly, "ID in use")
txt_id.Text = ""
txt_id.Focus()
Exit Sub
End If
Yes. I am using a library that almost nobody likes (COM / Interop). I am practicing doing a program that analize an Excel workbook, identify its columns and the user dials the type of each. Everything serves perfect, I can detect errors in the type of each column (for example if there is a string in a numeric column) but the only type that I am'm having problems is with dates. I asked a question here yesterday regarding dates (because I thought something) but I know from that question that dates are just numbers .... This is no problem because I can use Date.fromOADate.
Well, the situation I face is that if an Excel column contains information of dates and for example, you add a data string in that column of dates, when loading the Excel book in the program, that data string did not mark it as an error .. . but treats it as an empty cell (Thing that has surprised me).
this is the function that I wrote to mark the errors of each column
Protected Friend Function obtenerErroresColumna(ByVal column As String, ByVal page As String, ByVal tipe As String) As Integer
If (Not String.IsNullOrEmpty(column)) Then
Dim cmd As String = "Select [" & column & "] from [" & page & "$]"
Dim errors As Integer = 0
Dim table As New DataTable
Try
Dim adapter As New OleDbDataAdapter(cmd, conexion)
adapter.Fill(table)
adapter.Dispose()
For Each itm In table.Rows
If (tipe.Equals("String")) Then
If (Not IsDBNull(itm(0))) Then
If (IsNumeric(itm(0))) Then
errors += 1
setValueError = itm(0)
End If
End If
ElseIf (tipe.Equals("Numeric")) Then
If (Not IsDBNull(itm(0))) Then
If (Not IsNumeric(itm(0))) Then
errors += 1
setValueError = itm(0)
End If
End If
ElseIf (tipe.Equals("Date")) Then
If (Not IsDBNull(itm(0))) Then
If (Not IsDate(itm(0))) Then
errors += 1
setValueError = itm(0)
End If
End If
End If
Next
table.Dispose()
Return errors
Catch ex As Exception
boxMessage("Error", ex.Message, My.Resources._error).ShowDialog()
Return errors
End Try
Else
Return 0
End If
End Function
Ok, as I said the first two types is running good, the problem is when I start to compare date data type. I have this idea if the column is date type: If the program returns an empty cell (as I said earlier, the string data returns me as empty cells) then the program obtains the address of the cell to make a replacement. I have already written the method for substitution ... only as parameters would have to pass is today's date, the exact address of the cell and the column name.
I would like to check the adress of the current cell of the loop when the variable "itm" is Null (A4, B3, C50.... Etc)
I don't see any reference to Excel.Interop in your code. For the first 26 columns you can use Chr :
Dim adr = Function(col%, row%) Chr(64 + col) & row
Dim B3 = adr(2, 3) ' "B3"
Ok guys, I found the solution of this problem. I didnt use interop but I get what I wanted.
First I needed to get the letter according to the column name. I found the web a function that returns the column letters of excel by passing as a parameter one number
Private Function ColumnIndexToColumnLetter(colIndex As Integer) As String
Dim div As Integer = colIndex
Dim colLetter As String = String.Empty
Dim modnum As Integer = 0
While div > 0
modnum = (div - 1) Mod 26
colLetter = Chr(65 + modnum) & colLetter
div = CInt((div - modnum) \ 26)
End While
Return colLetter
End Function
I insert a counter in the function that detects errors, this counter would count the cells in the column while to get the column number, I create another function that carried the columns in a arrayList.
I take the indexOf function
Protected Friend Function obtenerErroresColumna(ByVal columna As String, ByVal hoja As String, ByVal tipo As String) As Integer
If (Not String.IsNullOrEmpty(columna)) Then
Dim cmd As String = "Select [" & columna & "] from [" & hoja & "$]"
Dim errores As Integer = 0
Dim tabla As New DataTable
Dim cell As Integer = 2
Dim column As New ArrayList
column = cargarMatrizColumnas(hoja)
Try
Dim adapter As New OleDbDataAdapter(cmd, conexion)
adapter.Fill(tabla)
adapter.Dispose()
For Each itm In tabla.Rows
If (tipo.Equals("Cadena")) Then
If (Not IsDBNull(itm(0))) Then
If (IsNumeric(itm(0))) Then
errores += 1
setValoresError = itm(0)
End If
End If
ElseIf (tipo.Equals("Numerico")) Then
If (Not IsDBNull(itm(0))) Then
If (Not IsNumeric(itm(0))) Then
errores += 1
setValoresError = itm(0)
End If
End If
ElseIf (tipo.Equals("Fecha")) Then
If (Not IsDBNull(itm(0))) Then
If (Not IsDate(itm(0))) Then
errores += 1
setValoresError = itm(0)
End If
Else
MsgBox("Direccion: " & ColumnIndexToColumnLetter(column.IndexOf(columna) + 1) & cell)
End If
cell += 1
End If
Next
tabla.Dispose()
Return errores
Catch ex As Exception
cajaMensaje("Error inesperado", ex.Message, My.Resources._error).ShowDialog()
PantallaPrincipal.lbldireccion.ForeColor = Color.Red
Return errores
End Try
Else
Return 0
End If
End Function
Source of the function: https://www.add-in-express.com/creating-addins-blog/2013/11/13/convert-excel-column-number-to-name/
I'm working on a project that displays text on a monitor as a reference but running into some logic trouble. Someone clicks a button which prompts an InputBox into which they insert a bar code with a scanner.
I have 2 types of part numbers, one is like this "11n11110mch" the other is something like this "12311110mch". I need code that tests whether the 3rd character is a number. The end goal is to display the number as "11.(some letter)111.10 MCH" and "123.111.10 MCH" in a TextBox. If I try "11n22210mch", I get an error that says
Conversion from string "n" to type 'Double' is not valid.
at
thirdChara = Mid$(VisPartID, 3, 1)
I am not sure how to correct this or accomplish what I am trying to do.
The code I have:
Public Sub btnScan_Click(sender As Object, e As EventArgs) Handles btnScan.Click
Dim ScanIDRaw As Object
'Clear Scan Value
ScanIDRaw = Nothing
'Display message, title, And default value.
ScanIDRaw = InputBox("Scan CDI", "InputBox")
Do Until ScanIDRaw IsNot ""
ScanIDRaw = InputBox("Part Number Needed, Scan CDI", "InputBox")
Loop
lblCDIPart.Text = ScanIDRaw
HUD.ReferenceCardDataPull()
End Sub
Public Async Sub ReferenceCardDataPull()
Dim PartID As String
Dim VisPartID As String
Dim thirdChara As String
'Other Code
'Something
'Something
VisPartID = Main.lblCDIPart.Text
thirdChara = Mid$(VisPartID, 3, 1)
If thirdChara = Not IsNumeric(thirdChara) Then
VisPartID = VisPartID.Insert(2, ".")
VisPartID = VisPartID.Insert(7, ".")
VisPartID = VisPartID.Insert(10, " ")
VisPartID = VisPartID.ToUpper
lblPart.Text = VisPartID
Else
VisPartID = VisPartID.Insert(3, ".")
VisPartID = VisPartID.Insert(8, ".")
VisPartID = VisPartID.Insert(11, " ")
VisPartID = VisPartID.ToUpper
lblPart.Text = VisPartID
End If
End Sub
If Not isNumeric(thirdChara) Then
But you really should be using VB.Net methods instead of the old VB6 style
dim position3 as integer
thirdChara = VisPartID.SubString(2,1) ' 2 because we're 0 based
if not integer.tryparse(thirdChara, position3) then
'do stuff if not a number
else
'it's a number
end if
The tryparse will return a boolean based upon the parse result. Upon successful parse, it will store the parsed value into the variable (in this case Position3)
I would also recommend turning on Option Strict as that would have informed you right away that you cannot implicitly convert a string to a boolean.
Meaning: The string thirdChara is being tested for equality against as Not (True|False) result from the IsNumeric method.
MVC 3. Vb.net. Part of my app generates PDF files using Itextsharp. Some strings are too long to go onto the background image correctly. So I basically need to split this string when its over 26 characters long and when it splits it cant split in the middle of a word. from there I will use newline to add the string to the right to the next line... Any ideas that might point me in the right direction.. I did start bulding the function that I will pass the string into test for length and then pass back the string after it finishes but I am stummped after that..
Private Function stringLength(ByVal _string As String) As String
If _string.Length < 26 Then
_string.Split(
End If
End Function
I'm sure there's a million different ways to do this.
You basically need to get all of your words split by the space into a list. After that, you just need to keep checking if the current word plus a space plus the next word reach your threshold or not, and if it does, you move to the next line. Once you have all of your lines, then you rejoin the list into a single string again.
Private Function LimitWidth(ByVal text As String, ByVal maxCharacters As Integer) As String
Dim words As List(Of String) = text.Split(" "c).ToList()
If text.Length < maxCharacters OrElse words.Count = 1 Then
Return text
Else
Dim lines As New List(Of String)
Dim currentLine As String = words(0)
For i As Integer = 1 To words.Count - 1
If (currentLine & " " & words(i)).Length > maxCharacters Then
lines.Add(currentLine)
currentLine = words(i)
If i = words.Count - 1 Then
lines.Add(currentLine)
End If
Else
If i = words.Count - 1 Then
lines.Add(currentLine & " " & words(i))
End If
currentLine &= " " & words(i)
End If
Next
Return String.Join(Environment.NewLine, lines.ToArray())
End If
End Function
To Test:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
MessageBox.Show(LimitWidth("This is a really long sentence " & _
"meant to demonstrate how to split " & _
"the words into a confined character length.", 26))
End Sub
It sounds like you are asking for a word wrap function.
Since I feel that it's better to answer in a way that promotes learning than to just give answers, I have for you a link that walks you through the process of using Test Driven Development (TDD) to solve this problem. It just so happens that the word wrap problem is a popular coding kata, and Robert C. Martin wrote a somewhat silly fictional story about a developer being taught how to use TDD to solve the word wrap kata.
The code examples are in Java, but it should be trivial to read and translate.
http://thecleancoder.blogspot.com/2010/10/craftsman-62-dark-path.html
The goofy bits are skip-able. Just jump down to the sentences right before the first code snippet.
I would add to it handling of multiline input text with following:
Private Function LimitWidth(ByVal text As String, ByVal maxCharacters As Integer, SplitSign As String) As String
Dim Output As String = ""
Dim OrgLines As List(Of String) = text.Split(Environment.NewLine).ToList()
For x As Integer = 1 To OrgLines.Count - 1
Dim words As List(Of String) = OrgLines(x).Split(" "c).ToList()
If text.Length < maxCharacters OrElse words.Count = 1 Then
Output += OrgLines(x)
Else
Dim lines As New List(Of String)
Dim currentLine As String = words(0)
For i As Integer = 1 To words.Count - 1
If (currentLine & " " & words(i)).Length > maxCharacters Then
lines.Add(currentLine)
currentLine = words(i)
If i = words.Count - 1 Then
lines.Add(currentLine)
End If
Else
If i = words.Count - 1 Then
lines.Add(currentLine & " " & words(i))
End If
currentLine &= " " & words(i)
End If
Next
Output += String.Join(SplitSign, lines.ToArray())
End If
Next
Return Output
End Function
use:
LimitWidth("your text", 80, Environment.NewLine)