numericals in word macro - vba

I have the task of finding numeric in a word document and alternatively superscript and subscript them.
I used this:
test = True
Dim chr As Range
For Each chr In ActiveDocument.Range.Characters
If IsNumeric(chr.Text) And test = True Then chr.Font.Subscript = True
test = False
If IsNumeric(chr.Text) And test = False Then chr.Font.Superscript = True
test = True
Next chr
This is only making all the numbers Superscript , not alternating between Super and Sub script
example Text -
" [17] Saied, M.H., Mostafa, M.Z., Abdel-Moneim, T.M., Yousef, H.A.: On Three Phase Six-
Switches Voltage Source Inverter: A 150° Conduction Mode. Member IEEE, Alexandria
Univercity (2006)"
now in tis example the macro would have to make 17 superscript and 150 subscript and 2006 as superscript..
Please someone help me with this

You could use Range.Characters to loop over the characters. Something like
Dim chr As Range
For Each chr In ActiveDocument.Range.Characters
If IsNumeric(chr.Text) Then chr.Font.SubScript = True
Next chr
Then add some booleans that tell you if you have to set it to sub- or superscript

if anyone needs the answer to this .. here is what I did ,
Selection.MoveUp Unit:=wdParagraph, Count:=2000
Dim vFindText As Variant
Dim vReplText As Variant
Dim i As Long
vFindText = Array("\[", "\] ", " \*")
vReplText = Array("", "", "")
With Selection
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Forward = True
.Wrap = wdFindStop
.MatchWholeWord = True
.MatchSoundsLike = False
.MatchAllWordForms = False
.MatchWildcards = True
.Format = True
.MatchCase = True
For i = 0 To UBound(vFindText)
.Text = vFindText(i)
.Replacement.Text = vReplText(i)
.Execute Replace:=wdReplaceAll
Next i
.Text = "[0-9]{1,}"
.Replacement.Text = "^&"
.Replacement.Font.Superscript = True
.Execute Replace:=wdReplaceAll, MatchWildcards:=True
End With
End With
MsgBox "Numbers has finshed , calling double1"
Call Numbers1
this will throw all numbers into subscript then it calls Sub Numbers1
Sub Numbers1()
Dim chr As Range
Dim firstChar As Word.Range
Dim test As Integer
test = 0
Dim firstAlphabet As Range
Selection.SetRange Start:=0, End:=100000
Set firstAlphabet = Selection.Range
For i = 2 To 1600
test = test + 2
Set firstChar = Selection.Characters(test)
If IsNumeric(firstChar.Text) Then firstChar.Font.Subscript = True
On Error Resume Next
Next i
End Sub
This will put all the numbers alternatively into subscript and superscript ....
The code can be optimized obviously ,,, at present it takes too long to do the given job ,,, but after searching for a working method all day, this is the only thing that works
hope this will help will Someone who comes finding this :)

Related

VBA Word: Insert text before found text in word document

What I want to do is something simple (maybe). I have written a find method to loop around the document. I have find value - ']' and insert value - '[('. In between those two there can be any kind of number most likely from 1 - 100.
My current code is this:
Sub FindBracket()
Dim FindValue As String
Dim ReplaceValue As String
Dim oRange As Range
Set oRange = ActiveDocument.Range
FindValue = "]"
InsertValue = "(["
With oRange.Find
.Text = FindValue
.MatchWholeWord = False
Do While .Execute = True
If .Found Then
oRange.InsertBefore (InsertValue)
End If
oRange.Start = oRange.End
oRange.End = ActiveDocument.Range.End
Loop
End With
End Sub
The find method works good, but I need to modify .InsertBefore method.
Example
I would need to transform ' Dummy text 1] ' to this ' Dummy text [(1] ' but from the code I get ' Dummy text 1[(] ', I cannot seem to figure out how to do that, and I have only previous experience with Excel VBA only.
Would appreciate any help on this, than you.
Try this:
Sub FindBracket()
Dim FindValue As String
Dim ReplaceValue As String
Dim oRange As Range
Set oRange = ActiveDocument.Content
FindValue = "[0-9]#\]"
InsertValue = "[(^&" ' ^& - found number
With oRange.Find
.Text = FindValue
.Replacement.Text = InsertValue
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True ' enabled regular expressions
.Execute Replace:=wdReplaceAll
End With
End Sub
Before:
Dummy text 1234]
Dummy text 4321]
Dummy text 0]
Dummy text 1]
After:
Dummy text [(1234]
Dummy text [(4321]
Dummy text [(0]
Dummy text [(1]
All you need is:
Sub FindBracket()
Application.ScreenUpdating = False
With ActiveDocument.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "[0-9]#\]"
.Replacement.Text = "[(^&"
.Forward = True
.Format = False
.Wrap = wdFindContinue
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
Application.ScreenUpdating = True
End Sub
Indeed, you don't even need a macro - it could all be done through the GUI using a wildcard Find/Replace with the same F/R expressions.

MS-Word(Mac) Type Case Macro - Fixing abbreviations with specific capitalized letters

I am trying to tweak/add to a type case macro I made and have been working on that I use in MS-Word (mac). I am trying to add to the macro to recognize specific abbreviations and convert them to a specific type case. For example, converting "ml" or "Ml" or "ML" to mL. Converting "gm" or "Gm" or "GM" to g.
I have attached my code below of what I have so far that fixes/ignores capitalizations, I just need help adding in these new rules. I am guessing I would have to create a bunch of specific If/Then statements, but I am not exactly sure.
Sub CaseFix()
'
' CaseFix Macro
'
'
Dim lclist As String
Dim wrd As Integer
Dim sTest As String
' list of lowercase words, surrounded by spaces
lclist = " of or the by your to this into at but with on compare compared is in for from a an and cm min minutes minute sec seconds mL gm g "
Selection.Range.Case = wdTitleWord
For wrd = 2 To Selection.Range.Words.Count
sTest = Trim(Selection.Range.Words(wrd))
sTest = " " & LCase(sTest) & " "
If InStr(lclist, sTest) Then
Selection.Range.Words(wrd).Case = wdLowerCase
End If
Next wrd
End Sub
For an existing document:
Sub CaseFix()
Application.ScreenUpdating = False
Dim FList As String, RList As String, j As Long
FList = "aaa,aba,aca,ada"
RList = "AAa,aBa,ACA,AdA"
With ActiveDocument.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Format = False
.Forward = True
.MatchWholeWord = True
.MatchWildcards = False
'Process each word from the Find/Replace Lists
For j = 0 To UBound(Split(FList, ","))
.Text = UCase(Split(FList, ",")(j))
.Replacement.Text = Split(RList, ",")(j)
.MatchCase = False
.Execute Replace:=wdReplaceAll
.MatchCase = True
.Execute Replace:=wdReplaceAll
Next
End With
Application.ScreenUpdating = True
End Sub
Note that you must have the same number of comma-separated entries in the FList and RList.

Word Macro - replace a fixed text with a variable that increase by a certain step

I have a word VBA that I want to make it a bit smarter. Right now, it serves me well but I still have to do a manual step, which I would like to eliminate. The macro replaces a string found in a selection. This string is "XXXX" which is found more than once. I prompt the user to enter a value for the variable that will replace the "XXXX". However, all the occurrences will be replaced by the same variable. I would like to be able to increase each instance by an increment of 2. So, if the user enters 402, I want the macro to find the first occurrence in the selection and replace it with 402, but the next occurrence should be replaced with 404, next 406, etc...
I tried to increment the "i" by two in the macro, but the macro goes ahead and replaces all the "XXXX" with the input variable. Any help or guidance would be very appreciated.
Here's my macro so far that needs to be enhanced.
Sub my_convert_to_PROCESS_steps_addBLOCKs()
'
' my_convert_to_PROCESS_steps Macro
'
'
Dim aRange As Range
Dim i As Integer
Dim intRowCount As Integer
Dim MyInput As Variant
intRowCount = 1
'Set aRange = ActiveDocument.Range
'Selection.WholeStory
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
Do
.Text = "XXXX " ' the word I am looking for
.Execute
If .Found Then
MyInput = InputBox(" ", "Process Block Sequence", "Enter Block Starting Number (e.g., 402)")
i = MyInput
.Replacement.Text = "At block " & i & ", the device may "
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = True
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
i = i + 2
End If
Selection.Find.Execute Replace:=wdReplaceAll
Loop While .Found
End With
End Sub
I was able to answer my own question. I had already worked on a similar one before. Here's the new code:
Sub my_convert_to_PROCESS_steps_addBLOCKs_new()
Application.ScreenUpdating = False
Dim i As Long
Dim MyInput As Variant
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "XXXX"
.Replacement.Text = ""
.Format = False
.Forward = True
.Wrap = wdFindStop
.MatchWildcards = True
.Execute
End With
MyInput = InputBox(" ", "Process Block Sequence", "Enter Block Starting Number (e.g., 402)")
i = MyInput
Do While .Find.Found
.Text = "At block " & i & ", the device may"
.Collapse wdCollapseEnd
.Find.Execute
i = i + 2
Loop
End With
Application.ScreenUpdating = True
End Sub

How to adjust the tracking settings for this macro?

I use the following macro to check documents for US spelling (referencing an installed custom dictionary) and run a ligatures check, replacing any applicable ligatures. It works well but a number of formatting changes show up on the right hand side of the document, including:
Formatted: Font 12 pt
Formatted: Font Not Italic
Field Code Changed
I'm OK with the above things being checked, but I don't want them to be shown in the tracking (only the ligature replacement tracking should be shown).
Could someone help me to adjust the following macro code so that only the replacement of the ligatures shows in the tracking? Many thanks in advance!
Sub USEnglish()
Selection.WholeStory
Dim i As Long, j As Long, k As Long
Dim StrFnd As String, StrRep As String
Dim ArrRep(), oSuggestions, Rng As Range
Application.CheckLanguage = False
Application.ResetIgnoreAll
Options.CheckGrammarAsYouType = True
Options.CheckGrammarWithSpelling = True
Options.ContextualSpeller = True
Options.CheckSpellingAsYouType = True
ArrRep = Array("ff", "fi", "fl", "ffi", "ffl")
With ActiveDocument
.TrackRevisions = True
.Range.LanguageID = wdEnglishUS
.SpellingChecked = False
.GrammarChecked = False
.ShowGrammaticalErrors = True
.ShowSpellingErrors = True
For i = 0 To UBound(ArrRep)
StrFnd = ChrW(&HFB00 + i)
StrRep = ArrRep(i)
For j = 1 To 3
On Error Resume Next
With .StoryRanges(j).Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = StrFnd
.Replacement.Text = StrRep
.Wrap = wdFindContinue
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
Next j
Next i
End With
End Sub
Just turn off formatting tracking and restore it when you've finished.
With ActiveDocument
.TrackFormatting = False
Field Code Changed is likely to be a result of the find and replace.

Find and Replace Single Digit numbers in MS Word

I am trying to locate single-digit numbers in MS Word (1-9) and replace it with word i.e. (1 = one, 2 = two). The current code replaces two-digit numbers and above. As of now, the only solution I can think of is to add spaces before and after the specific number but it is not that accurate.
Here is the code that I am using. TIA
Sub Single_Number()
Dim myDict: Set myDict = CreateObject("Scripting.Dictionary")
myDict("[1]{1}") = "one"
myDict("[2]{1}") = "two"
myDict("[3]{1}") = "three"
myDict("[4]{1}") = "four"
myDict("[5]{1}") = "five"
myDict("[6]{1}") = "six"
myDict("[7]{1}") = "seven"
myDict("[8]{1}") = "eight"
myDict("[9]{1}") = "nine"
Dim msword As Document, xWarp As Integer
For Each msword In Documents
msword.Activate
For myLoop = 0 To myDict.Count - 1
change_words myDict.Keys()(myLoop), myDict.Items()(myLoop)
Next
Next msword
End Sub
Function change_words(ByVal findWord, ByVal replaceWord)
If Selection.Type = wdSelectionIP Then
ActiveDocument.Range(0, 0).Select
xWarp = wdFindContinue
Else
xWarp = wdFindStop
End If
With Selection.Find
.ClearFormatting
.Text = findWord
.Replacement.Text = replaceWord
.Forward = True
.Forward = True
.Wrap = xWarp
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
End Function
Using the follow on string wasn't quite the best answer. The code below does the trick If and only if you only want to search in the main content of the document and your single digit numbers are preceded by a Space. If you are in the unfortunate position of having a single digit as the first character in a paragraph this code won't catch that issue. I'll leave it as an exercise to the reader as to how to modigy the () to include things such a paragraph markers.
The code below has been tested with
This 1 is 2 some 8 text 9. This is some7 more6 5 text
which is correctly converted as
This One is Two some Eight text Nine. This is some7 more6 Five text
This is the code
Sub ReplaceSingleNumbersWithText()
' Set up a search term for a single digit where the single digit is preceded
' by a space and followed by a character that is not a number or a letter
Const DIGIT_SEARCH As String = "( )([XXX]{1})([!0-9a-zA-Z])"
Dim myDigitAsWord As Variant
Dim mySearchDoc As Word.Document
Dim myIndex As Long
Dim myFindText As String
Dim myReplaceText As String
myDigitAsWord = Split("Zero,One,Two,Three,Four,Five,Six,Seven,Eight,Nine", ",")
For Each mySearchDoc In Word.Application.Documents
With mySearchDoc.StoryRanges(wdMainTextStory)
With .Find
.ClearFormatting
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
End With
For myIndex = 0 To UBound(myDigitAsWord)
myFindText = Replace(DIGIT_SEARCH, "XXX", CStr(myIndex))
myReplaceText = "\1" & myDigitAsWord(myIndex) & "\3"
.Find.Execute FindText:=myFindText, replacewith:=myReplaceText, Replace:=wdReplaceAll
Next
End With
Next
End Sub