Microsoft Office 2000/Visual Basic Programmer's Guide   

Adding and Removing Script from a Document

You add script to a document by using the Scripts collection's Add method. The Add method uses optional arguments that let you specify the script's location, language, ID attribute, additional <SCRIPT> tag attributes, and the script to be contained within the <SCRIPT> tags. The Add method also automatically generates HTML comment tags (<!-- and -->) around your script so that browsers that do not recognize script can ignore it. If you use the Add method without specifying any of the method's arguments, you create an empty <SCRIPT> tag pair that looks like this:

<SCRIPT ID="" LANGUAGE="VBScript">
<!--

-->
</SCRIPT>

You use the Anchor argument of the Add method to specify where the Script object should be located in a document.

Note   To see the Shape objects that are inserted when script is added to an Office document, point to Macro on the Tools menu, and then click Show All Script Anchors.

The following procedure uses the Scripts collection's Add method to add a <SCRIPT> tag pair and some Microsoft Visual Basic Scripting Edition (VBScript) code to the <HEAD> element of the current Word document:

Function AddScriptToDocumentDemo()
   ' This procedure illustrates how to use the Scripts collection
   ' to add VBScript code to an Office document.
   Dim strScriptCode As String
   Dim scrArrayScript As Script
   
   On Error Resume Next
   
   Set scrArrayScript = ActiveDocument.Scripts("scrDayArray")
   If Err = 0 Then
      ' The script is already in the document so no
      ' need to add it again.
      Exit Function
   End If
   
   strScriptCode = vbTab & "Option Explicit" & vbCrLf & vbTab _
      & "Dim arrDays(6)" & vbCrLf & vbTab _
      & "arrDays(0) = " & """Sunday""" & vbCrLf & vbTab _
      & "arrDays(1) = " & """Monday""" & vbCrLf & vbTab _
      & "arrDays(2) = " & """Tuesday""" & vbCrLf & vbTab _
      & "arrDays(3) = " & """Wednesday""" & vbCrLf & vbTab _
      & "arrDays(4) = " & """Thursday""" & vbCrLf & vbTab _
      & "arrDays(5) = " & """Friday""" & vbCrLf & vbTab _
      & "arrDays(6) = " & """Saturday"""
      
   With Application.ActiveDocument
      .Scripts.Add Location:=msoScriptLocationInHead, _
         Language:=msoScriptLanguageVisualBasic, ID:="scrDayArray", _
         ScriptText:=strScriptCode
   End With
End Function

The AddScriptToDocumentDemo procedure in the modAddScript module in ScriptSamples.doc in the ODETools\V9\Samples\OPG\Samples\CH06 subfolder on the Office 2000 Developer CD-ROM recreates the first script block shown in the HTML and script examples at the beginning of this section.

You can remove all the script and <SCRIPT> tags from a document by using the Scripts collection's Delete method. You remove a single script from the Scripts collection by using the Script object's Delete method.