Multiple index searches - vb.net

I have written a code to search for text using the index to not save to the listbox.
I need to add more characters to search.
I need to find the text starting with - and at the end -> this text is not written to the listbox.
They also need to find text beginning with / ** and at the end of * / but this code no longer works.
Dim openfile = New OpenFileDialog() With {.Filter = "Text (*.php)|*.php"}
If (openfile.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
For Each line As String In File.ReadAllLines(openfile.FileName, Encoding.Default)
'OPEN DIALOG
Next
End If
Dim komentar As Boolean
komentar = False
For Each line As String In File.ReadAllLines(openfile.FileName, Encoding.Default)
'FIND Charakter <!- and stop write to listbox
If Not line.IndexOf("<!-") = -1 Then
komentar = True
End If
If komentar Then --- this wrong
'FIND Charakter --> and afrer write to listbox
If Not line.IndexOf("-->") = -1 Then
komentar = False
End If
' I don't know how to specify another condition to search for other sentences
' that don't write when it finds characters
If Not line.IndexOf("/**") = -1 Then
komentar = True
End If
If komentar Then
If Not line.IndexOf("*/") = -1 Then
komentar = False
End If
Else
ListBox1.Items.Add(line)
End If
This code has the task of opening a file through a dialog box. Before it is loaded into the list box, it searches for text that begins with / ** and ends with * / and this text is not written to the listbox. I still need the listbox not to include sentences starting with so I used if not line.indexof and comment True or False.

I misunderstood your request at first but Andrew Morton's comment made me realise what you were actually asking for. Here's how I might implement it:
Dim terminatorsByInitiator As New Dictionary(Of String, String) From {{"<!--", "-->"},
{"/**", "*/"}}
Dim isComment = False
Dim terminator As String
For Each line In File.ReadAllLines(openfile.FileName, Encoding.Default)
If isComment Then
'Check whether we are at the end of the comment.
If line.EndsWith(terminator) Then
isComment = False
End If
Else
'Get the comment initiator at the start of the line, if there is one.
Dim initiator = terminatorsByInitiator.Keys.FirstOrDefault(Function(s) line.StartsWith(s))
If initiator Is Nothing Then
'This line does not initiate a comment so add it to the list.
ListBox1.Items.Add(line)
Else
'This line does initiate a comment.
isComment = True
'Remember which comment terminator to look for.
terminator = terminatorsByInitiator(initiator)
End If
End If
Next
The use of the Dictionary ensures that you always look for the right comment terminator based on the initiator that was found.

Related

Sub to find text in a Word document by specified font and font size

Goal: Find headings in a document by their font and font size and put them into a spreadsheet.
All headings in my doc are formatted as Ariel, size 16. I want to do a find of the Word doc, select the matching range of text to the end of the line, then assign it to a variable so I can put it in a spreadsheet. I can do an advanced find and search for the font/size successfully, but can't get it to select the range of text or assign it to a variable.
Tried modifying the below from http://www.vbaexpress.com/forum/showthread.php?55726-find-replace-fonts-macro but couldn't figure out how to select and assign the found text to a variable. If I can get it assigned to the variable then I can take care of the rest to get it into a spreadsheet.
'A basic Word macro coded by Greg Maxey
Sub FindFont
Dim strHeading as string
Dim oChr As Range
For Each oChr In ActiveDocument.Range.Characters
If oChr.Font.Name = "Ariel" And oChr.Font.Size = "16" Then
strHeading = .selected
Next
lbl_Exit:
Exit Sub
End Sub
To get the current code working, you just need to amend strHeading = .selected to something like strHeading = strHeading & oChr & vbNewLine. You'll also need to add an End If statement after that line and probably amend "Ariel" to "Arial".
I think a better way to do this would be to use Word's Find method. Depending on how you are going to be inserting the data into the spreadsheet, you may also prefer to put each header that you find in a collection instead of a string, although you could easily delimit the string and then split it before transferring the data into the spreadsheet.
Just to give you some more ideas, I've put some sample code below.
Sub Demo()
Dim Find As Find
Dim Result As Collection
Set Find = ActiveDocument.Range.Find
With Find
.Font.Name = "Arial"
.Font.Size = 16
End With
Set Result = Execute(Find)
If Result.Count = 0 Then
MsgBox "No match found"
Exit Sub
Else
TransferToExcel Result
End If
End Sub
Function Execute(Find As Find) As Collection
Set Execute = New Collection
Do While Find.Execute
Execute.Add Find.Parent.Text
Loop
End Function
Sub TransferToExcel(Data As Collection)
Dim i As Long
With CreateObject("Excel.Application")
With .Workbooks.Add
With .Sheets(1)
For i = 1 To Data.Count
.Cells(i, 1) = Data(i)
Next
End With
End With
.Visible = True
End With
End Sub

How to rename files listed at listbox?

I'm trying to create a little program thats introduce some prefixes into the name of the files that found at a folder.
The names of files are listed at a Listbox1 and the prefixes are choosed at a several Comboboxes.
This names of the Listbox1 with the choosed prefixes of the Comboboxes are moved to a Listbox2 pressing a buttom ">>>".
When all of new names are ready at this Listbox2 will be press a buttom "Rename" and the names of files at the folder will be changed according fixed at the Listbox2.
All of the Userform is already programmed. I have just problems to build the code for the buttom "Rename".
In others Words, taking the stipulate names of the Listbox2 and changing the names at the respective files showed before at the Listbox1.
How i can read the new names of files from a Listbox and introduce to the respective name of file?
Userform Screenshot
Code:
Sub cmdMoveSelLeft_Click()
'Variable Declaration
Dim iCnt As Integer
'Move Selected Items from Listbox1 to Listbox2
For iCnt = 0 To Me.ListNewFiles.ListCount - 1
If Me.ListNewFiles.Selected(iCnt) = True Then
Dim changedName As String
changedName = Me.ComboBoxKategorie.Value + "_" + Me.ComboBoxTyp.Value + "_" + Me.ListNewFiles.List(iCnt)
Me.ListChangedFiles.AddItem changedName
End If
Next
For iCnt = Me.ListNewFiles.ListCount - 1 To 0 Step -1
If Me.ListNewFiles.Selected(iCnt) = True Then
Me.ListNewFiles.RemoveItem iCnt
End If
Next
ComboBoxKategorie = ""
ComboBoxTyp = ""
TextBoxEXX = ""
TextBoxUX = ""
TextBoxTrakt = ""
TextBoxGebaude = ""
TextBoxSpecific = ""
Sub cmdRename_Click()
Dim Msg = 'Möchten Sie fortfahern?'
Response = MsgBox(Msg, Style, Title, Help, Ctxt)
If Response = vbYes Then ' User chose Yes.
~?????????????~
MsgBox "Die Namen sind angepasst" & vbCrLf
Unload Me
End If
End Sub
Use the Name keyword like
Name "C:\Post IN\BEISPEIL_SAN_SP_U2" As "C:\Post IN\AUS_BPH_BEISPEIL_SAN_SP_U2"
Of course you won't use string literals like that, but I can't tell where you have the old name and the new name. Generally, the syntax is
Name "FullPathOfExistingName" As "FullPathOfNewName"

ActiveX Checkbox calls Sub to loop through all Bookmarks and perform conditional action (to specific group)

I'm using VBA in Word to create a SmartForm where the user can tick a checkbox in order to display certain information which I have Bookmarked using the naming format "TEXT_BUTANE"
Because each product (BUTANE/ PROPANE/ ETHANE) will have multiple Bookmarks throughout the document I'm naming them "TEXT_BUTANE1" "TEXT_BUTANE2" etc
So I'd then like to loop through all Bookmarks and hide/show sections in the document depending on which group it belongs to i.e all Bookmarks starting with "TEXT_BUT" would be considered a group that would be collectively hidden (or shown if checked)
I'm getting a compile error "Next without For" but from what I can see the syntax is correct
It was working before creating the LoopThroughBookmarks Sub, but I need something like this so I can hide/show multiple sections of the document
Any help would be much appreciated
Private Sub CHECK_BUTANE_Click()
Dim vw As Word.View
Dim bChecked As Boolean
Dim bkm As Word.Bookmark
'turned on non-printing characters individually so that
'not displaying Hidden text does not affect these settings.
Set vw = Application.ActiveWindow.View
If vw.ShowAll = True Then 'if TRUE then SHOW following
vw.ShowParagraphs = True
vw.ShowObjectAnchors = True
vw.ShowTabs = True
vw.ShowHyphens = True
vw.ShowOptionalBreaks = True
vw.ShowSpaces = True
End If
vw.ShowAll = False 'if FALSE then HIDE following
vw.ShowHiddenText = False
bChecked = Me.CHECK_BUTANE.Value
'if CHECKED
If bChecked Then
Call LoopThroughBookmarks("BUT", True) 'then TRUE so loop through bookmarks passing PRODUCT
Else
Call LoopThroughBookmarks("BUT", False) 'then FALSE so loop through bookmarks passing PRODUCT
End If
End Sub
Public Sub LoopThroughBookmarks(product As String, bChecked As Boolean)
Dim bkm As Bookmark
Dim strMarks() As String
Dim intCount As Integer
Dim checkString As String
Dim bkmName As String
checkString = "CHECK_" + product 'CHECK_BUT or CHECK_PRO or CHECK_MET
If ActiveDocument.Bookmarks.Count > 0 Then
ReDim strMarks(ActiveDocument.Bookmarks.Count - 1)
intCount = 0
For Each bkm In ActiveDocument.Bookmarks 'Set bkm to be current Bookmark
bkmName = Left$(bkm.Name, 9) 'taking first 9 chars for bkm comparison
If bkmName = checkString Then 'if TRUE
bkm.Range.Font.Hidden = Not bChecked 'then hidden is false
Else 'is FALSE
bkm.Range.Font.Hidden = bChecked 'so stay visibility
Next bkm
End If
End Sub
You are probably getting that error because you are missing an End If immediately before the Next in this part of your code:
If bkmName = checkString Then 'if TRUE
bkm.Range.Font.Hidden = Not bChecked 'then hidden is false
Else 'is FALSE
bkm.Range.Font.Hidden = bChecked 'so stay visibility
Next bkm
As a further observation, you could probably simplify this part of your code
bChecked = Me.CHECK_BUTANE.Value
'if CHECKED
If bChecked Then
Call LoopThroughBookmarks("BUT", True) 'then TRUE so loop through bookmarks passing PRODUCT
Else
Call LoopThroughBookmarks("BUT", False) 'then FALSE so loop through bookmarks passing PRODUCT
to
Call LoopThroughBookmarks("BUT",Me.CHECK_BUTANE.Value)

Using a swear word filter with InStr in Visual Basic 2012

I want to compare the IF argument to a string array. The user will try to put in a teamname into a textbox, if the user uses a swear word anywhere within that textbox, it will display an error message and clear the textbox. If the user has not sworn, it will register the teamname and carry on with the program (As can be seen in the 2nd IF statement). I have tried to get this code to work for a week now and cannot get it to work.
Private Sub SelectionButtonEnter_Click(sender As Object, e As EventArgs) Handles SelectionButtonEnter.Click
Dim HasSworn As Boolean = False
Dim swears() As String = {"Fuck", "fuck", "Shit", "shit", "Shite", "shite", "Dick", "dick", "Pussy", "pussy", "Piss", "piss", "Vagina", "vagina", "Faggot", "faggot"} 'Declare potential swear words the kids can use
For Each swear As String In swears
If InStr(SelectionTextBoxTeamName.Text, swear) > 0 Then
SelectionTextBoxTeamName.Clear() 'Clear the textbox
MessageBox.Show("Remember ... You can be disqualified, raise your hand and Blair will set up the program for you again") 'Let the user know they have entered a swear word and ask them to select another team name
End If
If Not InStr(SelectionTextBoxTeamName.Text, swear) > 0 Then
Timer1.Enabled = True 'Enable timer 1 for the learn box
Timer3ForSelection.Enabled = True 'Enable this timer to show the learn button
TeamName = SelectionTextBoxTeamName.Text() 'Once this button has been pressed, store the content of that textbox in a the TeamName string
SelectionLabelTeamName.Text = "Welcome " & SelectionTextBoxTeamName.Text & " Please click 'Learn' in the box below to begin" 'Display the contents of the string along with other text here
SelectionLabelTeamNameTL.Text() = "Team Name: " & TeamName 'Display the contents of the string along with other text here
SelectionTextBoxTeamName.BackColor = Color.Green 'Have the back color of the box set to green
SelectionTextBoxTeamName.Enabled = False 'Do not allow the user/users enter another team name
End If
Next 'A next must be declared in a for each statement
End Sub
Thanks in advance.
I don't think I'd approach it that way; if the user types f**kyou, your code wouldn't catch it. How about this instead:
In your code:
If ContainsBannedWord(SelectionTextBoxTeamName.Text) Then
Msgbox "Hold out your hand, bad person. SlapSlapSlap"
Else
Msgbox "Good boy!"
End if
Function ContainsBannedWord(sInput As String) As Boolean
Dim aBannedWords(1 To 5) As String
Dim x As Long
' Make all the banned words capitalized
aBannedWords(1) = "BANNED1"
aBannedWords(2) = "BANNED2"
aBannedWords(3) = "BANNED3"
aBannedWords(4) = "BANNED4"
aBannedWords(5) = "BANNED5"
For x = LBound(aBannedWords) To UBound(aBannedWords)
If InStr(UCase(sInput), aBannedWords(x)) > 0 Then
ContainsBannedWord = True
Exit Function
End If
Next
ContainsBannedWord = False
End Function

msgbox dilemma with translator app

I am building language translator for my tribe. I have about 90% it completed. the only problem i am having is that i want to have msgbox pop up and say "translation not found.", when someone enters a phrase or a word that can't be found in the text file which is read " cat | nish stu yah." I can have it pop up when the translation isn't found, but here is the problem when i type in a word that is found the msgbox pop up as well. I dont know if it has to do with that it is running a do while (true) loop or i am just not coding the translator button correctly. the code is:
Do While (True)
Dim line As String = reader.ReadLine
If line Is Nothing Then
Exit Do
End If
Dim words As String() = line.Split("|")
Dim word As String
For Each word In words
If word = TextBox1.Text Then
TextBox2.Text = words(+1)
Else
MessageBox.Show("Translation is not available")
End If
If "" = TextBox1.Text Then
MessageBox.Show("No entry was made.")
End If
Next
Loop
Assuming your file format is:
cat | nish stu yah
with the spaces around the | character, your issue is probably that String.Split will not remove the spaces, so in this case you will end up with:
words(0) = "cat "
words(1) = " nish stu yah"
So, if TextBox1.Text is "cat", it will not match. You could change the comparison to something like this, to make it more forgiving:
If word.Trim().ToLower() = TextBox1.Text.Trim().ToLower() Then
However, you don't really need to loop through words, since you only want to compare the user input against the untranslated version. You are also showing the message box for each line in the translation file. I think you probably want something like this (completely untested):
If "" = TextBox1.Text Then
MessageBox.Show("No entry was made.")
Exit Sub
End If
Dim found As Boolean = False
Do While (True)
Dim line As String = reader.ReadLine()
If line Is Nothing Then
Exit Do
End If
Dim words As String() = line.Split("|"c)
If words(0).Trim().ToLower() = TextBox1.Text.Trim().ToLower() Then
TextBox2.Text = words(1)
found = True
Exit Do
End If
Loop
If Not found Then
MessageBox.Show("Translation is not available")
End If
Still not the most elegant code, but hopefully points you in the right direction.