PDA

View Full Version : How to check is any macros exist in un-saved document



Frobs
11-26-2009, 03:19 AM
Hi

I am currently creating a customized Save As button for Word 2007 and want to check if the un-saved document contains a macro or not. If it contains a macro the document is saved as .DOCM and if not it's saved as .DOCX.

Can any one help?

/Frobs

macropod
11-26-2009, 05:53 PM
Hi Frobs,

You shouldn't need to check - using File|Save As (which is what one would ordinarily use when saving a new document) automatically defaults to the docm format if the document has a vba module.

Frobs
11-27-2009, 01:11 AM
Hi

Thanks for the input.

I started out by using this code to do the save as:
ActiveDocument.SaveAs FileName:=MainFolderName & tmpSaveAs, FileFormat:=wdFormatText
But I found out that the "FileFormat" should either be wdFormatXMLDocument or wdFormatXMLDocumentMacroEnabled to save as .docx and .docm.
With some more testing I found out that I could leave out the "FileFormat" and then Word would figure out which format to use but that is not working quit as I am expecting.

I have created a macro and added a button to the quick launch and saved the template in the "Word\Start" folder. This is working fine but if I create a new document and record a macro in the new document and then uses my custom save as button it always saves the file as .docx which will delete my macro.

If I open op the template with my Save As macro and quick launch button and run the custom save as macro it actually saves the file as a .dotm so something is working.

And that's the reason for me wanting to check if a document contains a macro so that I can select what format to save as.

I hope this makes sense :-)

/Frobs

macropod
11-27-2009, 03:01 AM
Hi Frobs,

You could use something along the lines of:
Sub Demo()
Dim MainFolderName As String, tmpSaveAs As String
MainFolderName = "D:\Misc Files\"
tmpSaveAs = "MyFile"
With ActiveDocument
If .VBProject.VBComponents.Count > 1 Then
.SaveAs FileName:=MainFolderName & tmpSaveAs, FileFormat:=wdFormatXMLDocumentMacroEnabled, AddToRecentFiles:=False
Else
.SaveAs FileName:=MainFolderName & tmpSaveAs, FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False
End If
End With
End SubNote: this will only work if your vba project is trusted - see http://support.microsoft.com/kb/282830

TonyJollans
11-29-2009, 04:19 PM
The way to check is:

If ActiveDocument.HasVBProject Then
' save as docm
Else
' save as docx
End If

macropod
11-29-2009, 04:23 PM
Hi Tony,

Much better!

Frobs
11-29-2009, 11:29 PM
Hi Tony and Macropod,

Thanks for both your inputs.

Tony, your suggestion was spot on, it now implemented and working great :-)

/Frobs