VBA - Check if ContentControl text contains formatting? - vba

So this is what I want to do, if it's possible.
I've got a lot of rich textboxes in a Word template. And I want to create a macro that basically checks if any characters in the text entered into the placeholder is formatted with superscript, subscript, bold or underline etc.
So, What I've got so far is this
Dim i As Long
Dim txtboxString as String
For i = 1 To ActiveDocument.ContentControls.Count
If ActiveDocument.ContentControls(i).Title = "Repporttitle" Or ActiveDocument.ContentControls(i).Title = "Subtitle" Then
If ActiveDocument.ContentControls(i).LockContentControl = True Then
ActiveDocument.ContentControls(i).LockContentControl = False
End If
txtboxString = ActiveDocument.ContentControls(i).Range.Text
End If
Next i
So, now, txtboxString contains the text that was typed into the placeholder. But I want to check each letter for it's formatting. The method above only gives me the text as a simple text string. I've seen that I can check each letter of the string this way:
Dim counter as integer
Dim contentText as string '(this is passed on via the above txtboxString)
Dim letter as string
For counter = 1 To Len(contentText)
letter = Mid(contentText, counter, 1)
Next
But, this won't give me the formatting of each letter. How can I do that?

Use Characters and Font instead of Text. Like this:
Sub GetCharacterFormatting()
Dim i As Long
Dim txtboxString As Characters ''# <- this was changed from "String" to "Characters"
Dim Bold As String
Dim Italic As String
Dim Subscript As String
Dim CharacterFont As Font
Dim ap As Document: Set ap = ActiveDocument
For i = 1 To ap.ContentControls.Count
If ap.ContentControls(i).Title = "Repporttitle" Or ap.ContentControls(i).Title = "Subtitle" Then
If ap.ContentControls(i).LockContentControl = True Then
ap.ContentControls(i).LockContentControl = False
End If
txtboxString = ap.ContentControls(i).Range.Characters ''# <- this was changed from "Text" to "Characters"
Dim counter As Integer
For counter = 1 To txtboxString.Count
Index = counter
CharacterText = txtboxString(i).Text
CharacterFont = txtboxString(i).Font
''# You can just grab all the formatting for the character or use If/Then statements
Bold = "Bold: " & CharacterFont.Bold & ", "
Italic = "Italic: " & CharacterFont.Italic & ", "
Subscript = "Subscript: " & CharacterFont.Subscript & " "
''#
Next
Debug.Print Index & " (" & CharacterText & ") : " & Bold; Italic; Subscript
End If
Next i
End Sub

Related

MS- Access VBA Converting multiple characters to Asc

For a homework project I am trying to enter characters in a single textbox as (eg:"AbC" no spaces) and have the output in a captioned label as the corresponding ASCII value written out with commas and spaces. (eg: 65, 98, 67)
Private Sub cmdCode_Click()
Dim codeInt As Integer
strInput = txtInput.value
codeInt = Asc(strInput)
lblAnswer.Caption = codeInt & ", "
End Sub
I would like the result to look like: 65, 98, 67
I'm getting no errors but only receiving "65," as my output.
Here is my solution. It assumes that the input is always going to be three (3) characters long:
Private Sub cmdCode_Click()
Dim x As String
Dim y As String
Dim z As String
strInput = txtInput.value
x = Asc(Left(strInput, 1))
y = Asc(Mid(strInput, 2, 1))
z = Asc(Right(strInput, 1))
lblAnswer.Caption = x & ", " & y & ", " & z
End Sub
This can be done for generic usage - and a little smarter:
Public Function StrToAscList( _
ByVal Text As String) _
As String
Dim Chars() As Byte
Dim Item As Integer
Dim List As String
Chars() = StrConv(Text, vbFromUnicode)
For Item = LBound(Chars) To UBound(Chars)
If Item > 0 Then List = List & ", "
List = List & CStr(Chars(Item))
Next
StrToAscList = List
End Function
Then:
Me!lblAnswer.Caption = StrToAscList(strInput)

How to apply text formatting to a listbox in Microsoft Access using VBA?

I would like to remove comma or period and capitalize the first letter of last name, I can only do with a textbox which I have to insert last name every time
Here is my code for the textbox:
Private Sub Command2_DblClick(Cancel As Integer)
Text19 = Trim(Text19)
If Right(Text19, 1) = "." Or Right(Text19, 1) = "," Then
Text19 = Left(Text19, Len(Text19) - 1)
End If
Text19 = UCase(Left(Text19, 1)) & Mid(Text19, 2)
End Sub
How should the code be changed if I want to apply to a listbox?
Edited for listbox use.
Public Sub CapitalizeListBox(PListBox As ListBox)
Dim i, ListItem As Integer
Dim Lname() As String
Dim TempString As String
For ListItem = 0 To PListBox.ListCount - 1
Lname = Split(PListBox.ItemData(ListItem), " ") ' Break the name into words
For i = LBound(Lname) To UBound(Lname) 'for each word, capitalize first letter
Lname(i) = UCase(Left(Lname(i), 1)) & Mid(Lname(i), 2)
Next i
TempString = ""
For i = LBound(Lname) To UBound(Lname) 'Reassemble the name in the textbox
TempString = TempString & " " & UCase(Left(Lname(i), 1)) & Mid(Lname(i), 2)
Next i
TempString = Trim(TempString)
PListBox.RemoveItem (ListItem)
PListBox.AddItem TempString, ListItem
Next ListItem
End Sub

VBA Code for cell data language translation

I'm writing a code to translate data from a selected cell from Portuguese to English, but I'm stuck with an error:
The translated cell is returning just "and" no matter what I write, it should translate all the words in a cell... Any ideas brilliant minds?
Here is my code:
Sub traducaobeta()
Dim translate As Object 'scritping.Dictionary
Set translate = CreateObject("Scripting.Dictionary")
translate("cadeira") = "chair"
translate("cadeiras") = "chairs"
translate("criado mudo") = "night stand"
translate("criado-mudo") = "night stand"
translate("mesa") = "table"
translate("mesas") = "tables"
translate(" e ") = " and "
' the list goes on...
Dim ptWords As String
Dim enWords As String
ptWords = LCase(activecell.Value)
For Each tempVar In translate.Keys()
enWords = Replace(Replace(CStr(tempVar), CStr(tempVar), translate(CStr(tempVar)), InStr(CStr(tempVar), CStr(tempVar))), " e ", " and ")
activecell.Offset(0, 1).Value = enWords
Next
End Sub
Anyone knows how to fix it?
I would try a loop through the words in your text instead.
The following procedure translates every word that is found in your collection and leaves other words in portuguese:
Sub traducaobeta()
Dim translate As Object 'scritping.Dictionary
Set translate = CreateObject("Scripting.Dictionary")
translate("cadeira") = "chair"
translate("cadeiras") = "chairs"
translate("criado mudo") = "night stand"
translate("criado-mudo") = "night stand"
translate("mesa") = "table"
translate("mesas") = "tables"
translate(" e ") = " and "
' the list goes on...
Dim Words As Variant
Dim I As Integer
Words = Split(LCase(ActiveCell.Value))
For I = LBound(Words) To UBound(Words)
If translate(Words(I)) <> "" Then Words(I) = translate(Words(I))
Next
ActiveCell.Offset(0, 1).Value = Join(Words)
End Sub
The error is telling you that you must use a Variant type variable in a For Each loop. You're using ptWords which is a String but the values returned from translate.Keys() are not explicit string types which causes an error.
Either declaring the variable as a variant
Dim ptWords As Variant
Or using a generic variant in your loop:
For Each tempVar In translate.Keys()
enWords = Replace(Replace(CStr(tempVar), CStr(tempVar), translate(CStr(tempVar)), InStr(CStr(tempVar), CStr(tempVar))), " e ", " and ")
activecell.Offset(0, 1).Value = enWords
Next
Should do the trick.
Note that I've explicitly cast tempVar to a string in the code using CStr() - whilst this may not always be necessary (due to implicit type conversion) it is a good practice to get into.

Showing the difference between two RichTextBox controls

I'm trying to compare both richtextbox text and show the difference into the 3rd richtextbox. After i do some changes to the code that i get from this forum, it still have some problems, which is there are words that are no different showing out at my 3rd richtextbox.... the right hand side of the rich text box is from a text file that have been checked in regex function before displayed in the box.
this is the source code that use for compare:
Dim txt1(DispBox.Text.Split(" ").Length) As String
Dim txt2(DispBox2.Text.Split(" ").Length) As String
txt1 = DispBox.Text.Split(" ")
txt2 = DispBox2.Text.Split(" ")
Dim diff1 As String = "" 'Differences between 1 and 2
Dim diff2 As String = "" 'Differences between 2 and 1
Dim diffPosition As Integer ' Set where begin to find and select in RichTextBox
diffPosition = 1 ' Initialize
For Each diff As String In txt1
If Array.IndexOf(txt2, diff.ToString) = -1 Then
diff1 += diff.ToString & " "
With DispBox
.Find(diff, diffPosition, RichTextBoxFinds.None) ' Find and select diff in RichTextBox1 starting from position diffPosition in RichtextBox1
.SelectionFont = New Font(.Font, FontStyle.Bold) ' Set diff in Bold
.SelectionColor = Color.Blue ' Set diff in blue instead of black
.SelectionBackColor = Color.Yellow ' highlight in yellow
End With
End If
diffPosition = diffPosition + Len(diff) ' re-Initialize diffPostion to avoid to find and select the same text present more than once
Next
DispBox3.Visible = True
DispBox3.Text = diff1
this is my upload button code to check the regex function
Dim result As DialogResult = OpenFileDialog1.ShowDialog()
' Test result.
If result = Windows.Forms.DialogResult.OK Then
' Get the file name.
Dim path As String = OpenFileDialog1.FileName
Try
' Read in text.
Dim text As String = File.ReadAllText(path)
Dim postupload As String = Regex.Replace(text, "!", "")
DispBox2.Text = postupload
' For debugging.
Me.Text = text.Length.ToString
Catch ex As Exception
' Report an error.
Me.Text = "Error"
End Try
End If
because inside the text file there will be "!" between the line, I would like to replace the "!" with "breakline/enter".
My problem is :
why the "Building & hostname" words count as wrong words.
why the new word that display in 3rd richtextbox is not in new line if the words is found in the middle of the line.
the other wrong words are not color, bold n highlight.....
Your code is splitting all the words based on a space, but it's ignoring the line breaks, so it makes "running-confing building" look like one word.
Try it this way:
Dim txt1 As String() = String.Join(" ", DispBox.Lines).Split(" ")
Dim txt2 As String() = String.Join(" ", DispBox2.Lines).Split(" ")

How To Replace or Write the Sentence Backwards

I would like to have a block of code or a function in vb.net which can write a sentence backwards.
For example : i love visual basic
Result : basic visual love i
This is what I have so far:
Dim name As String
Dim namereversed As String
name = RichTextBox1.Text
namereversed = ""
Dim i As Integer
For i = Len(name) To 1 Step -1
namereversed = namereversed & Replace(name, i, 1)
Next
RichTextBox2.Text = namereversed
The code works but it does not give me the value of what i want. it makes the whole words reversed.
Dim name As String = "i love visual basic"
Dim reversedName As String = ""
Dim tempName As String = ""
For i As Integer = 0 To name.Length - 1
If Not name.Substring(i, 1).Trim.Equals("") Then
tempName += name.Substring(i, 1)
Else
reversedName = tempName + " " + reversedName
tempName = ""
End If
Next
start from index 0 and deduct 1 from length because length count starts with one but index count starts with zero. if you put To name.Length it will return IndexOutOfBounds. Loop it from 0 To Length-1 because you need the word as is and not spelled backwards... what are placed in reverse are the words so add a temporary String variable that stores every word and add it before the saved sentence/words.
or use this
Dim strName As String() = name.Split(" ")
Array.Reverse(strName)
reversedName = String.Join(" ", strName)
This is my contribution, well as you can see its not hard to do, its really simple. There are a lot of other ways which are more short.
Console.Title = "Text Reverser"
Console.ForegroundColor = ConsoleColor.Green
'Text which will be Reversed
Dim Text As String
Console.Write("Write your text: ")
Text = Console.ReadLine
Console.Clear()
Dim RevText As String = "" '← The Text that will be reversed
Dim Index As Int32 = Text.Length '← Index used to write backwards
'Fill RevText with a char
Do Until RevText.Length = Text.Length
RevText = RevText.Insert(0, "§")
Loop
Console.WriteLine(RevText)
'Replace "Spaces" with Character, using 'Index' to know where go the chars
For Each Caracter As Char In Text
Index -= 1 'Rest 1 from the Index
RevText = RevText.Insert(Index, Caracter) '← Put next char in the reversed text
'↓ Finished reversing the text
If Index = 0 Then
RevText = RevText.Replace("§", "") 'Replace char counter to nothing
Console.WriteLine("Your text reversed: " & RevText) '← When Index its 0 then write the RevText
End If
Next
'Pause
Console.ReadKey()
I've done this project in a console, but you know, you can use this code in a normal Windows Form.
This is my first Answer in Stackoverflow :)