Search code examples
vbaformatword-2007

macro to return active document format for IF/Then statement


I am creating a document template for a report for my staff to use and I have a command button at the bottom that will delete all of the command buttons in the report and protect it as read only to close out the report.

I don't want someone accidentally making these changes to the template if they happen to open that instead of a new document based on it.

So I would like a string of code that checks the active document, if it is .dotm I want it to display a message box and exit. if it is a .docx I want it to continue with the rest of the code I have written.

I have been unable to return the format or use it in an IF/THEN statement. I have been unable to find anything on the net on this either. Is it impossible? or should I be checking for the file extension? If so how would I use that as a value in an IF/THEN Statement?


Solution

  • The document may have been based on the template, but not yet saved. In which case it would be called "Document1", etc., without a dot.

    If InStr(ActiveDocument.Name,".") = 0 Then
        'it is a new document, based on a template
    ElseIf InStr(ActiveDocument.Name,".dotm") > 0 Then
        'it is a/the template
    

    This of course assumes that the ActiveDocument is the correct one. If they click a button in the document then this is correct, but if they use the Macros dialog then you may want to include additional checks.

    I would use the following, which ignores differences in case (.dotm, .DOTm):

    If InStr(UCase(ActiveDocument.Name), ".DOTM") > 0 Then
        'it is a template..
    Else
        'it's just a document
    End If
    

    Checking ActiveDocument.AttachedTemplate.Name can also be useful, to confirm if the active-document is one based on your template.