Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing internal link to Word-templates via VBA

Tags:

ms-word

vba

I'm trying to create a small VB-application that removes the internal link in Word Documents, to their templates.

I have found this guide http://word.tips.net/Pages/T001437_Batch_Template_Changes.html and am trying to modify it, to use with VBA instead of Macro programming inside of Office.

However, I'm getting stuck on how to get the Document.Open to work. Any help is appreciated.

This is supposed to run as a free-standing application, and not runt from within Word. I'm looking for a way to perform what the Macro does, but not from within Word.

like image 437
Gnutt Avatar asked Dec 04 '25 14:12

Gnutt


2 Answers

There are two pieces of bad news to give here.

1) A document has to have a template. You cannot remove it, only change it to something else.

2) Changing a template does nothing anyway. See this page.

I am wonder if the problem with the Open method is that you are trying to open ".doc" extension files, not the modern ".docx" extension files. The VBA subroutine you linked to only does ".doc" files. This VBA code does both:

Function StringEndsWith( _
    ByVal strValue As String, _
    CheckFor As String) As Boolean

  Dim sCompare As String
  Dim lLen As Long

  lLen = Len(CheckFor)
  If lLen > Len(strValue) Then Exit Function
  sCompare = Right(strValue, lLen)
  StringEndsWith = StrComp(sCompare, CheckFor, vbTextCompare) = 0
End Function


Sub ChangeTemplates()
    Dim strDocPath As String
    Dim strTemplateB As String
    Dim strCurDoc As String
    Dim docCurDoc As Document

    ' set document folder path and template strings
    strDocPath = "C:\tmp\"

    ' get first doc - only time need to provide file spec
    strCurDoc = Dir(strDocPath & "*.doc*")

    ' ready to loop (for as long as file found)
    Do While strCurDoc <> ""
        If (StringEndsWith(strCurDoc, ".doc") Or StringEndsWith(strCurDoc, ".docx")) Then
            ' open file
            Set docCurDoc = Documents.Open(FileName:=strDocPath & strCurDoc)
            ' change the template back to Normal
            docCurDoc.AttachedTemplate = ""
            ' save and close
            docCurDoc.Close wdSaveChanges
        End If
        ' get next file name
        strCurDoc = Dir
    Loop
    MsgBox "Finished"
End Sub
like image 103
Simon G. Avatar answered Dec 07 '25 05:12

Simon G.


long time between answers but may be useful to others. If you have access to the VBE of the Word document [Alt F11], and you want to remove the reference then go to "Tools/References" [top menu] and deselect it from the list of reference files. I had a similar issue where template no longer existed, but it was still being 'referenced' in the Project window, so I did the above.

like image 29
NeilS Avatar answered Dec 07 '25 04:12

NeilS