Please Help
Please Help

Reputation: 1

Open Microsoft Word and type text with SendKeys

I am trying to create a VBScript that opens Word and inputs text into it.

My code:

::Set wshshell = WScript.CreateObject("WScript.Shell")
::Set objShell = CreateObject("WScript.Shell")
::objShell.AppActivate "word"
::userProfilePath = objShell.ExpandEnvironmentStrings("%UserProfile%")
::WScript.Sleep 10000
::wshshell.SendKeys "Hello World!"

Upvotes: 0

Views: 2082

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200453

Perhaps surprisingly, you cannot interact with Word unless you actually started the program in the first place. As documented the AppActivate method activates an application window, i.e. brings the window of an already running application to the foreground.

To start Word programmatically use something like this:

Set wd = CreateObject("Word.Application")
wd.Visible = True

You can open a document like this:

Set doc = wd.Documents.Open("C:\path\to\your.docx")

or create a new document like this:

Set doc = wd.Documents.Add

Text can be entered for instance via the TypeText method:

doc.Selection.TypeText "some text"

Save the document like this:

doc.Save
doc.Close

or like this (if it's a new document or you want to save it under a different name/path):

doc.SaveAs "C:\path\to\new.docx", 16
doc.Close

Exit from the application like this:

wd.Quit

Do NOT use SendKeys for anything. EVER. Not unless you're being forced at gunpoint.

Also do NOT write Frankenscript that mixes different languages (like batch and VBScript) in the same file. It's a pain in the rear to debug and maintain.

Upvotes: 1

Related Questions