View Single Post
 
Old 12-07-2016, 08:56 AM
gmayor's Avatar
gmayor gmayor is offline Windows 10 Office 2016
Expert
 
Join Date: Aug 2014
Posts: 4,142
gmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud ofgmayor has much to be proud of
Default

You can use following macro in the template to write the macros the document requires, to the document, which must then be saved as a macro enabled document in order for those macros to work in the document.

The function copies the code from a text file, stored locally, to the document that requires the macros. This is essentially the process used in http://www.gmayor.com/interactive_multichoice.html, though that uses a password protected document to hold the code rather than a text file - the text file is quicker.

In the example below, the macro code clears the named module of the document, then writes the text from the text file to it.

Code:
Public Function AddVBACodeFromTXT(oDoc As Document, strSource As String, strModule As String)
Dim strLines As String
Dim i As Long, j As Long
Dim strCode As String
Dim iFile As Integer: iFile = FreeFile

Open strSource For Input As #iFile
strCode = Input(LOF(iFile), iFile)
Close #iFile

    i = oDoc.VBProject.VBComponents(strModule).CodeModule.CountOfLines
    oDoc.VBProject.VBComponents(strModule).CodeModule.DeleteLines 1, i
    oDoc.VBProject.VBComponents(strModule).CodeModule.AddFromString strCode
lbl_Exit:
    Exit Function
End Function

Sub Example()
    AddVBACodeFromTXT ActiveDocument, "E:\Path\Forum\Test\Code.txt", "ThisDocument"
End Sub
__________________
Graham Mayor - MS MVP (Word) (2002-2019)
Visit my web site for more programming tips and ready made processes www.gmayor.com
Reply With Quote