启用宏的word文档可以保存更改对话框

时间:2014-09-10 06:38:35

标签: vba ms-word word-vba

我有一个VBA脚本如下。

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

这里的宏运行正常,但问题是当我打开并关闭我的word文档时,虽然没有进行任何更改,但它会询问我是否要保存下面的更改。

enter image description here

如果文档中没有更改,请告诉我如何避免使用此保存对话框。

如果我打开一个空白文档并关闭它,即使这样也会被触发。

1 个答案:

答案 0 :(得分:1)

正如评论中所述,在AutoOpen中创建变量会导致此行为。

在AutoOpen中包含Save语句:

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

避免保存提示。