Highlight in yellow a word in a string (sentence) - excel

I create a small word document from excel in vba. I would like to highlight in yellow a word in a sentence. Currently, it is what I am doing:
wdDoc.Content.Paragraphs.Last.Range.Characters(60).Shading.BackgroundPatternColor = wdColorYellow
...which is good for one character, but not great for several characters. In my case, I am highlighted a word of 7 characters which is feasible by repeating this line above and changing the index.
But, I am curious and would like to know if there is a better way to do it.
Thanks.

I tested this little snippet. It determines the position of the 60th character of the past paragraph within the document and then sets a range starting from there.
Dim wdDoc As Document
Dim p As Long
Set wdDoc = ActiveDocument
p = wdDoc.Paragraphs.Last.Range.Characters(60).Start
wdDoc.Range(p, p + 7).Shading.BackgroundPatternColor = wdColorYellow
There should be an easier way to do this but I didn't find it.

Related

How do you get the different ThemeFonts used in a text in excel?

In Excel, I have a text in a cell that has two different fonts. One of them is variable, be it arial or calibri, and the other is Symbol. I need to be able to detect the symbol font and what is within it.
I've tried to check for characters with values above 122, but these are just regular text values with a different font.
I tried using ThemeFont, such as
Dim WhatIsFont As ThemeFont
WhatIsFont = Worksheets("MySheet").Range("A1").Font.ThemeFont
But it returns Nothing when I this variable.
And if I use WhatIsFont as a String, it instead gives me a numeric value between 0 and 2 based on what kind of fonts and how many are used.
I cannot, for the life of me, find any other function that deals with ThemeFonts and know which ones exactly are being used.
Anyone knows how to do this?
Thank you.
After a while of playing around, I found an answer to my own question through the following code:
Sub TestFont()
'
' TestFont Macro
'
'
Dim i As Long
Dim r As Range
ThisWorkbook.Worksheets("Instructions").Range("C11").Select
For Each r In Selection
For i = 1 To Len(r.Value)
With r.Characters(i, 1).Font
MsgBox .Name
End With
Next i
Next r
End Sub
To answer my question then. ThemeFont won't cut it. Its .Font.Name that gives you the actual font being used here. By cycling through the several characters in a string - rather than investigate the string as a whole - you can pinpoint the Font name of each character, and thus from there single out the ones written in Symbol!

Finding a character count in Word VBA

I'm trying to dynamically generate a word document from an excel spreadsheet. The way that I am going about doing it now is basically manually finding character count, and then will eventually insert a given item at that specific character count. The given item is stored in excel. So it would be like:
Spreadsheet
| 1 | 2 | 3
Char | 50 | 125 | 250
Item | Hello | Darkness | Friend
And then in the word VBA, use
Dim myCheck As ContentControl
Dim myRange As Range
Dim rng As Long
rng = ''whatever char is for that column
Set myRange = ActiveDocument.Range(start:=rng, End:=rng)
Set myCheck = ActiveDocument.ContentControls.Add(wdContentControlCheckBox, myRange)
'what I am doing now is adding a check box dynamically at a given position on the range. This can be either checkboxes that are added or text or whatever.
The issue is: how do I find locate a specific point on the a word document? The form that I am trying to insert these into is static, so I can safely assume that if I want to insert it at character 100, each time I make a new form it will insert it in the same place.
I tried using 'word count' character button, but that didn't seem to be accurate. It was consistently 40 or so characters in front of where I wanted it to be. Didn't see a pattern.
Is there an easy way to place my cursor at a location on a document and know how many characters came before it, as counted by the range object? Or is there a more efficient way of locating things on a word document, provided that I cannot alter the word document itself in appearance (can't add grids, grid layouts, tables, or anything like that).
I believe the bookmark functionality is what you're looking for.
You can create bookmarks in a static Word Document beforehand and use them as your insertion target... or you can create the bookmarks programmatically with VBA and then use the insert text option.
Examples for using a bookmark to insert text.
Sub InsertAtBookmarkI()
ActiveDocument.Bookmarks("bmAtBookmark").Range.InsertAfter "Some text here"
End Sub
MSDN Document for creating bookmarks programmatically.
Sub Mark()
ActiveDocument.Bookmarks.Add Name:="mark"
End Sub
Sub ThirdPara()
Dim myDoc As Document
' To best illustrate this example,
' Letter.doc must be opened, not active,
' and contain more than 3 paragraphs.
Set myDoc = Documents("Letter.doc")
myDoc.Bookmarks.Add Name:="third_para", _
Range:=myDoc.Paragraphs(3).Range
myDoc.ActiveWindow.View.ShowBookmarks = True
End Sub

How do I search for numbers within a range that are written in a specific format?

I am trying to write an Excel formula that measures the number of times a number between 1000 and 9999 is written in text using the format 0,000. (This is being used to read old content from our website and measure how many pages do not align with a new style guide.) Here is what I have so far:
=count(search(text(1000,"0,000"),G17))
This formula works if the text in the content is 1,000, but, obviously, not if the text is 1,001.
I don't know how to enter the range in. I assume it should go where the 1000 is, but nothing I try works.
Does anyone know how to do this?
If your text-based number values in column G are between 0 and 999,999 then this should return a count of all text-based numbers that would have a numerical value between 1000 and 9999 if they were actually numbers.
=SUMPRODUCT(COUNTIF(G:G, {"1,*","2,*","3,*","4,*","5,*","6,*","7,*","8,*","9,*"}))
Another approach is that anything between 1,000 and 9,999 is going to have a length of 5.
=SUMPRODUCT(--(LEN(G:G)=5))
If you add the following code to a new "Module" in the VBA Editor you will have access to it as a worksheet function.
I've not tested it all that much but it worked for my example.
Public Function RESearch(SourceText) As Integer
Dim REO As Object: Set REO = CreateObject("VBScript.RegExp")
REO.Pattern = "(\d{1},\d{3})"
REO.Global = True
REO.IgnoreCase = False
REO.MultiLine = True
Dim Matches As Variant
Set Matches = REO.Execute(SourceText)
RESearch = Matches.Count
Set REO = Nothing
End Function
This will add a function "RESearch" to the workbook, and should return the count of all numbers that match the pattern.
Try this:
=COUNTIF(G:G,"?,???")

Add a space after colored text

I'm Using Microsoft Excel 2013.
I have a lot of data that I need to separate in Excel that is in a single cell. The "Text to Columns" feature works great except for one snag.
In a single cell, I have First Name, Last Name & Email address. The last name and email addresses do not have a space between them, but the color of the names are different than the email.
Example (all caps represent colored names RGB (1, 91, 167), lowercase is the email which is just standard black text):
JOHN DOEjohndoe#acmerockets.com
So I need to put a space after DOE so that it reads:
JOHN DOE johndoe#acmerockets.com
I have about 20k rows to go through so any tips would be appreciated. I just need to get a space or something in between that last name and email so I can use the "Text to Columns" feature and split those up.
Not a complete answer, but I would do it way:
Step 1 to get rid of the formatting:
Copy all text that you have to the notepad
Then copy-paste text from Notepad to excel as text
I think this should remove all the formatting issues
Step 2 is to use VBA to grab emails. I assume that you have all your emails as lowercase. Therefore something like this should do the trick (link link2):
([a-z0-9\-_+]*#([a-z0-9\-_+].)?[a-z0-9\-_+].[a-z0-9]{2,6})
Step 3 is to exclude emails that you extracted from Step2 from your main text. Something like this via simple Excel function:
=TRIM(SUBSTITUTE(FULLTEXT,EMAIL,""))
Since you removed all the formatting in Step1, you can apply it back when you done
You can knock this out pretty quickly taking advantage of a how Font returns the Color for a set of characters that do not have the same color: it returns Null! Knowing this, you can iterate through the characters 2 at a time and find the first spot where it throws Null. You now know that the color shift is there and can spit out the pieces using Mid.
Code makes use of this behavior and IsNull to iterate through a fixed Range. Define the Range however you want to get the cells. By default it spits them out in the neighboring two columns with Offset.
Sub FindChangeInColor()
Dim rng_cell As Range
Dim i As Integer
For Each rng_cell In Range("B2:B4")
For i = 1 To Len(rng_cell.Text) - 1
If IsNull(rng_cell.Characters(i, 2).Font.Color) Then
rng_cell.Offset(0, 1) = Mid(rng_cell, 1, i)
rng_cell.Offset(0, 2) = Mid(rng_cell, i + 1)
End If
Next
Next
End Sub
Picture of ranges and results
The nice thing about this approach is that the actual colors involved don't matter. You also don't have to manually search for a switch, although that would have been the next step.
Also your neighboring cells will be blank if no color change was found, so it's decently robust against bad inputs.
Edit adds ability to change original string if you want that instead:
Sub FindChangeInColorAndAddChar()
Dim rng_cell As Range
Dim i As Integer
For Each rng_cell In Range("B2:B4")
For i = 1 To Len(rng_cell.Text) - 1
If IsNull(rng_cell.Characters(i, 2).Font.Color) Then
rng_cell = Mid(rng_cell, 1, i) & "|" & Mid(rng_cell, i + 1)
End If
Next
Next
End Sub
Picture of results again use same input as above.

How to parse in VBA a string that contains Mathematics special ASCII code and correct it

I'm currently writing a code in VBA to retrieve prices for some financial models. The problem I have is in the excel spreadsheet where I have special Ascii characters like ⅞ ¼ etc...
I would need using VBA to transform this in 7/8 1/4 etc...
How could I do that ?
Thanks for your help
If you want literal string replacement, use the Replace function thus:
Sub changeit()
Dim w As Worksheet
Dim r As Range
For Each r In Application.Selection
r.Value = Replace(r.Value, Chr$(188), "1/4")
r.Value = Replace(r.Value, Chr$(189), "1/2")
r.Value = Replace(r.Value, Chr$(190), "3/4")
Next
End Sub
et cetera. (I have done each one separately to make it easier to read.) Alternatively, you could replace the literal strings "1/4" as #jalexiou suggests with 0.25 etc., ideally using a lookup table. Not sure what the Chr$ code is for the seven-eighths though.
Create a lookup table. When it finds one of these special characters set the value appropriately (example "1/2" = 0.5) and if not use the Val() function to get the value.

Resources