user3872094
user3872094

Reputation: 3351

Macro enabled word documents give save changes dialogue

I've a VBA script as below.

Sub AutoOpen()
  ActiveDocument.Variables("LastOpen").Value = Now()
End Sub

Sub AutoClose()
  Dim objFSO, objFolder, objTextFile, objFile
  Dim strDirectory, strFile, strText
  strDirectory = "d:\work"
  strFile = "\work.csv"

  ' Create the File System Object
  Set objFSO = CreateObject("Scripting.FileSystemObject")

  ' Check that the strDirectory folder exists
  If objFSO.FolderExists(strDirectory) Then
     Set objFolder = objFSO.GetFolder(strDirectory)
  Else
     Set objFolder = objFSO.CreateFolder(strDirectory)
     Debug.Print "Just created " & strDirectory
  End If

  If objFSO.FileExists(strDirectory & strFile) Then
     Set objFolder = objFSO.GetFolder(strDirectory)
  Else
     Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
     Debug.Print "Just created " & strDirectory & strFile
  End If

  Set objFile = Nothing
  Set objFolder = Nothing
  ' OpenTextFile Method needs a Const value
  ' ForAppending = 8 ForReading = 1, ForWriting = 2
  Const ForAppending = 8

  Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)

  'Build the string to write
  strText = """" & ActiveDocument.FullName & """" & "," & ActiveDocument.Variables("LastOpen").Value & "," & Now()

  ' Writes strText every time you run this VBScript
  objTextFile.WriteLine (strText)
  objTextFile.Close
End Sub

here the macro is running fine, but the problem is when i open and close my word document, though there are no changes done, it asks me if i would like to save the changes like below.

enter image description here

please let me know how can i avoid this save dialogue box, if there are no changes made in document.

here if i open a blank document and close it, even then this is getting triggered.

Upvotes: 0

Views: 559

Answers (1)

joeschwa
joeschwa

Reputation: 3175

As mentioned in comments, the creation of the variable in AutoOpen is causing this behavior.

Include a Save statement in AutoOpen:

Sub AutoOpen()
  ActiveDocument.Variables("LastOpen").Value = Now()
  ThisDocument.Save
End Sub

to avoid the Save prompt.

Upvotes: 1

Related Questions