Microsoft Word另存为宏返回损坏的文件

时间:2018-10-01 17:19:40

标签: vba ms-word

我有一个Word文档,正在将其用作其他项目的模板。该文件另存为.docx,并包含一个宏来保存文档,该宏的文件名取决于标题为“ STATE”的内容控制框。我希望宏保存不包含宏的文档。当我运行宏时,文档将保存到正确的文件位置,但是在打开时,我看到一条错误消息:

  

很抱歉。我们无法打开FILE LOCATION,因为我们发现其内容存在问题。没有可用的错误详细信息。

我认为我的代码中某处有错误。我正在使用Word2013。任何帮助将不胜感激!

Sub Silent_save_to_DOC()

Dim strText As String, strDate As String, strDrop As String

strText = ActiveDocument.SelectContentControlsByTitle("STATE")(1).Range.Text

Dim strFilename As String
strFilename = "C:\Users\Tom\Desktop\Quote - " & strText & ".docx"
ThisDocument.SaveAs strFilename

End Sub

2 个答案:

答案 0 :(得分:3)

问题在于* .docx文件可能不包含宏,只有* .docm文件可能包含宏。您的代码迫使Word使用宏和不兼容的文件扩展名保存文档。作为安全措施,Word不会打开包含宏的* .docx文件-消息会通知您。

使用真实的模板文件-* .dotm-创建文档。模板可以包含宏,这些宏将复制到文档中。

如果要从文档中取消链接(带有宏),可以将普通模板附加到文档(ActiveDocument.AttachedTemplate = NormalTemplate)。

使用SaveAs时,请确保还使用FileFormat参数(而不仅仅是文件名)指定文件格式。对于将是^ wdFormatXMLDocument`的docx文件。

不要不要使用ThisDocument.SaveAs,因为ThisDocument是指包含宏的文档。相反,如果您不能另外使用特定的ActiveDocument对象,请使用Document

答案 1 :(得分:0)

如果您指定文件格式(如果保存格式与打开的文件格式不同),这也很有帮助。因此:

Dim strText As String, strFilename As String
With ActiveDocument
  strText = .SelectContentControlsByTitle("STATE")(1).Range.Text
  strFilename = "C:\Users\Tom\Desktop\Quote - " & strText & ".docx"
  .SaveAs2 FileName:=strFilename, FileFormat:=wdFormatXMLDocument
End With