[VBScript] Accessing (Office) applications programmatically

Discussion in 'Archives' started by Flopper, Mar 8, 2011.

[VBScript] Accessing (Office) applications programmatically
  1. Unread #1 - Mar 8, 2011 at 1:58 PM
  2. Flopper
    Joined:
    Feb 28, 2011
    Posts:
    42
    Referrals:
    0
    Sythe Gold:
    0

    Flopper Member

    [VBScript] Accessing (Office) applications programmatically

    Yoohoo.

    Introduction
    This is a short guide that gives an example on how to access the Office component model from a script. What I love about VBScripts is that every modern Windows PC can run it, and you can write it from Notepad.

    Why?
    One example of where this procedure comes into great use is in cases where macros and VBA code have been disabled in Office. Have you made some neat macro that extends the functionality of Excel, but your school policy blocks VBA? VBScript doesn't care.

    Requirements
    * Windows 98 or higher (to run VBScripts)
    * Microsoft Office (to program for it, obviously ^_^)

    Here we go!
    You can control almost every element of an Office application's document interface, but for this example, we're just going to insert text into a Word document.

    1) Start Notepad (if you're lazy, hold Windows button + R and type 'notepad')
    2) Start out by writing the following on the first line of the text file:
    Code:
    set wApp = CreateObject("Word.Application")
    This line of code accesses the Word component model and creates a new object. In other words, this is how we start our Word application from the outside. You can also access an already existing session - won't cover that for now.

    3) Now, start a new line in the text file and add this:
    Code:
    wApp.Visible = True
    Since we've only created the Word session, this line makes it visible.

    4) Then, add the following (each line separated by line break):
    Code:
    set wDoc = wApp.Documents.Add
    We're creating a local variable called 'wDoc' which becomes a reference to the new document we're adding through the Word application variable's ('wApp') 'Documents' collection.

    Code:
    wDoc.Paragraphs(1).Range.Text = "Hello, Word!"
    This line accesses the newly added document's first paragraph. In the Office object model, most placeholders are accessed through the 'Range' property.

    The result is the following:
    Code:
    set wApp = CreateObject("Word.Application")
    wApp.Visible = True
    set wDoc = wApp.Documents.Add
    wDoc.Paragraphs(1).Range.Text = "Hello, Word!"
    5) Save the Notepad textfile with the '.vbs' extension. For example, Save As and type 'MyScript.vbs' and save it.
    6) Run your script and watch the magic!
     
< What's best payment method? [ANTISCAM] | How to make Chocolate cake in a coffee mug! >

Users viewing this thread
1 guest


 
 
Adblock breaks this site