Making a macro only work on certain files

Joined
Nov 11, 2022
Messages
4
Reaction score
0
Hi, I have a macro that updates all fields and saves the doc on close. This happens with any word doc. I would like it to only happen on documents that begin with "interior." . How should I put that in here? The macro uses a class module which is out of my depth.

Here is what is in the regular module:

Option Explicit
Dim objWordClass As New objWordClass
Public Sub AutoOpen()
Set objWordClass.objWord = Word.Application
End Sub


Here is what is in the class module:


Option Explicit
Public WithEvents objWord As Word.Application

Private Sub objWord_DocumentBeforeClose(ByVal objDoc As Document, varCancel As Boolean)
Dim strButtonValue As String


Application.ScreenUpdating = False
Set objDoc = ActiveDocument
objDoc.Save
strButtonValue = MsgBox("Do you want to update all fields in this document before closing?", _
vbYesNo + vbQuestion)
If strButtonValue = vbYes Then
varCancel = True
If objDoc.Fields.Count > 0 Then
With objDoc
.Fields.Update
If objDoc.Indexes.Count > 0 Then _
If objDoc.Range(Start:=objDoc.Indexes(1).Range.Start - 50, End:=objDoc.Indexes(1).Range.Start).Words.Last = "Index" Then _
objDoc.Range(Start:=objDoc.Indexes(1).Range.Start - 50, End:=objDoc.Indexes(1).Range.Start).Words.Last.Style = "Heading 1,Heading 1 Char Char Char,Heading 1 Char Char"
.Save
.Close
End With

Else
MsgBox ("There is no field in this document.")
End If
Else
varCancel = False
End If

Application.ScreenUpdating = True

End Sub
 

macropod

Microsoft MVP
Joined
Mar 2, 2012
Messages
580
Reaction score
50
For example, taking an entirely different approach:
Code:
Private Sub Document_Close()
Application.ScreenUpdating = False
With ActiveDocument
  If .Range.Words.First = "interior" Then
    .Fields.Update
    .PrintPreview
    .ClosePrintPreview
  End If
End With
Application.ScreenUpdating = True
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top