This is my first time attempting VBA in Word although I've used it quite a bit in Excel. What I am trying to do is automatically execute my code after opening my Word template document. Here is the code I've placed in my Word template Module:
Private Sub AutoOpen()
Dim myValue
myValue = InputBox(prompt:="What is the client name", Title:="InputBox", Default:="Type your client name here")
stringReplaced = stringReplaced + "<Replace>"
For Each myStoryRange In ActiveDocument.StoryRanges
With myStoryRange.Find
.Text = "<Replace>"
.Replacement.Text = myValue
.Wrap = wdFindContinue
.ClearFormatting
.Replacement.ClearFormatting
.Replacement.Highlight = False
.Execute Replace:=wdReplaceAll
End With
Next myStoryRange
End Sub
I am using Word 2010. My code runs like I want it to when I manually go in and click run. However, when I close out of my Word document and reopen nothing happens at all. I've Googled the problem trying to find out a solution (and have attempt different versions of AutoOpen), but I can't figure out what I am doing wrong. Any ideas on why the AutoOpen doesn't execute automatically?
Thanks!
You should place your code in standard Module in your Template document. Next, change sub name from AutoOpen() into:
Sub AutoExec()
'..... your code here .....
End Sub
Related
I am trying to find a selection of text in a Word document and then lock the content control.
I have one search text 'Our Ref:' and another 'Your Ref:'.
When the second sub searches for 'Our Ref:' it also highlights 'Your Ref:'.
Screenshot of search result for 'our ref:'
I tried to add .MatchPrefix which works within the advanced find in Word, but not in the macro.
Is there a way to either skip the first result or narrow the search?
Private Sub LockOurRef()
With Selection.find
.Text = "Our Ref:"
.MatchWholeWord = True
.Forward = True
.Execute
Selection.Range.ContentControls.Add (wdContentControlGroup)
Selection.ParentContentControl.LockContentControl = True
End With
End Sub
I am executing a style search in Microsoft Word using a VBA Macro.
My goal is to perform certain actions once for every style found in the document.
The macro works correctly on documents that have at least two paragraphs, but the macro does not alert the style correctly in a document that has exactly one paragraph in it. It seems strange that when I enter a new paragraph mark, the styles are found, even though I did not add any new text or styles to the document, just an extra blank paragraph mark. Does anyone know what is wrong with my macro and how I can fix this? Thanks for taking a look.
Sub AlertAllStylesInDoc()
Dim Ind As Integer
Dim numberOfDocumentStyles As Integer
Dim styl As String
Dim StyleFound As Boolean
numberOfDocumentStyles = ActiveDocument.styles.count
For Ind = 1 To numberOfDocumentStyles
styl = ActiveDocument.styles(Ind).NameLocal
With ActiveDocument.Content.Find
.ClearFormatting
.text = ""
.Forward = True
.Format = True
.Style = styl
Do
StyleFound = .Execute
If StyleFound = True Then
' actual code does more than alert, but keeping it simple here'
MsgBox styl
GoTo NextStyle
Else
Exit Do
End If
Loop
End With
NextStyle:
Next
End Sub
I don't understand why ActiveDocument.Content is not working, but replacing it with ActiveDocument.Range(0,0) appears to resolve the issue (tested in Word 2016).
With ActiveDocument.Range(0, 0).Find
Currently this code runs with no error message but does not make the requested replacement:
Private Sub TestingButton_Click()
Dim RngFound As Range
Dim FileToProcess As Word.Document
Dim WordInstance As Object
Set WordInstance = CreateObject("Word.Application") 'For these tests I close Word first.
Set FileToProcess = WordInstance.Documents.Open("c:\sarah\junk\Attach.doc")
WordInstance.ActiveDocument.Range.Select 'Gets the whole document
Toolbox.SetupFind (WordInstance.ActiveDocument.Range)
With WordInstance.ActiveDocument.Range.Find
.Text = "rock"
.Replacement.Text = "found it!"
.Execute
End With
End Sub
In the Toolbox module:
Public Function SetupFind(ByRef RngPassed As Word.Range)
With RngPassed.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = ""
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute
End With
End Function
The code above is from a test database that I created for troubleshooting. My destination is an Access form whose purpose is to extract some information from a set of documents, and place the information in a database. It was working fine. It stopped working after a particularly spectacular crash. I tried to remove a label while the form was in break mode. (I know,... deep regret) I couldn't close Access even with ctrl-break. Probably the wierdest part is that similar code now no longer works in back-up copies of the database either.
Here are things I've tried that haven't worked:
Re-import all objects into a new database.Similarly, rebuild the backend database. Break the form's code (a couple thousand lines)
into modules. Copy all the code into Notepad, save it, then create a
button in a new empty database. Recreate subs & functions by
typing, then once they exist, paste in the code from Wordpad. Reset
the form's references, which include MSWord. Make a brand new form
in the new database with one button that has only the displayed
code. Use a defined range: This all started when I got a persistent
error in RngToSearch.find.execute findtext:="reason". The error
highlighted .find and said 'Argument not optional.' So among other
things, I switched to a selection rather than a defined range in my
attempts to isolate the problem. But working with a range rather
than a selection is where I really need to end up again.
Possibly relevant observations:
Other forms in the same database with lots of backend code work fine. So do other routines in the same form.
Only one document is open. As far as I can tell, there's nothing unusual about the document. I have tried multiple documents.
The text to find exists in the document, outside of a table.
Things that have worked, as they might be clues:
In Word straight up, no code, no nothing, use 'find' to select the targeted word.
WordInstance.ActiveDocument.Range.Text = Replace(WordInstance.ActiveDocument.Range.Text, "rock", "Found it!"). Trouble is, what I ultimately need to do again is way more complex than Replace can handle.
Specify the scope for the replacement(s). The code worked for me from Access 2010 with this change in TestingButton_Click() ...
'.Execute
.Execute Replace:=wdReplaceAll
Toolbox.SetupFind also calls .Execute. Since the find and replacement text are both empty strings at that point and no scope is specified, .Execute doesn't cause harm ... but it doesn't seem useful either.
I need to add correct stress accents to every word in a Microsoft Word document. I have a script called "DoAccentuate" which determines the correct accentuation for any word that is input. However, I don't know how to capture the currently selected found word, process it with my DoAccentuate script, and replace that same word with the result (without effecting the formatting of the text). This is what I tried.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim document As Word.Document
document = Globals.ThisAddIn.Application.ActiveDocument
Dim FindObject As Word.Find = document.Application.Selection.Find
With FindObject
.ClearFormatting()
.Text = "<*>"
.MatchWildcards = True
.Replacement.ClearFormatting()
.Replacement.Text = DoAccentuate(document.Application.Selection.Text)
.Execute(Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
End With
End Sub
Lets pretend for now this is your DoAccentuate script:
Private Function DoAccentuate(theWordToAccentuate As String)
theWordToAccentuate = theWordToAccentuate + "`"
DoAccentuate = theWordToAccentuate
End Function
Given this, the find/replace can be as simple as:
Public Sub FindWordAndReplaceWithAccentuatedForm()
Dim accentuatedText As String: accentuatedText = DoAccentuate(Selection.text)
Selection.Find.text = Selection.text
Selection.Find.Replacement.text = DoAccentuate(Selection.text)
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
This should not remove any formatting.
I am assuming that you desire a solution which requires user to select the word they want to accentuate, and then run the macro (since your method above assumes this ie: .Replacement.Text = DoAccentuate(document.Application.Selection.Text
I'm trying to write a macro that displays a popup when a user clicks save (I have it as Sub FileSave() ) if the document contains any highlighting. So far, everything works great with the message box. Unfortunately I can't figure out which conditions to use for the if statement to check whether the document contains highlighting or not.
Can anyone help me with a few lines of VBA for this?
You simply need to search for highlighted text within document content in this way:
Sub SearchAnyHighlight()
Dim hiliRng As Range
Set hiliRng = ActiveDocument.Content
With hiliRng.Find
.Highlight = True
.Execute
End With
If hiliRng.Find.Found Then
'to inform that something was found
MsgBox "You can't close Active Document"
'to remove all highlighted area <-- added after edition
With hiliRng.Find
.Replacement.Highlight = False
.Execute "", Replace:=wdReplaceAll, Forward:=True, _
ReplaceWith:="", Format:=True
End With
End If
End Sub