CreateObject("WScript.Shell") is Nothing error - vbscript

I have a script below:
Dim g_oWShell
Set g_oWShell = CreateObject("WScript.Shell")
But when I validate the value of g_oWShell first, that object is null (nothing). Below are the codes I'm debugging:
If g_oWShell Is Nothing Then
'display an error.
Else
'run Something... (Ex. g_oWShell.Run("...")
End If
I'm new to VBS and I'm not sure why is that the case. I have read a short definition of CreateObject method here: VBA CreateObject
Advance thanks for explaining what might I have missed.
EDIT:
I'm creating an MSI installer using Visual Studio.

Related

How to automatically close an OK window in VBScript?

I need to automatically close an "OK" window in a program by pressing Enter.
I tried to do that with a VBScript, but it gives me an error.
Set objshell = WshShell.Sendkeys "{Enter}" ("wscript.shell")
objshell.Run,0, True
exit
The error is:
Line: 1
Char: 34
Error: End of instruction expected
Code: 800A0401
Source: Microsoft Vbscript Compile Error
When in doubt, read the documentation. There is no intrinsic object WshShell in VBScript. You need to create a WScript.Shell instance and assign it to that variable before you can call the SendKeys method on it.
Set WshShell = CreateObject("WScript.Shell")
WshShell.SendKeys "{Enter}"
And you probably need to bring the window to which you're trying to send that keystroke to the front first using AppActivate.
Anyway, seeing how all of your 3 lines of code are entirely broken syntactically, I strongly recommend you go find a VBScript tutorial before proceeding any further.
Note also that SendKeys is a horribly unreliable method of automation. You may want to look into something like AutoIt instead.

How to close an application when vbscript crashes

I'm using VBscript to open Microsoft Excel and convert xls documents to csv.
Here is a quick example that takes an argument and converts the first page
Dim oExcel
Dim oBook
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Open(Wscript.Arguments.Item(0))
oBook.SaveAs "out.csv", 6
oBook.Close False
oExcel.Quit
If everything works, that's great. But when the script crashes before it can close excel, the process continues to stay around and lock the file until I manually kill the process.
How can I make sure that I perform any clean up routines even when the script fails?
As the question is/was? about closing Excel reliably when the VBScript used to automate it crashes:
If you write
Set oExcel = CreateObject("Excel.Application")
you create a 'simple' variable. VBScript may decrement a ref counter when the variable goes out of scope, but it certainly won't .Quit Excel for you.
If you want a feature like atexit calls or exception handling in VBScript, you'll have to write a class that 'does what I mean' in its Class_Terminate Sub. A simple example:
Option Explicit
Class cExcelWrapper
Private m_oExcel
Public Sub Class_Initialize()
Set m_oExcel = CreateObject("Excel.Application")
End Sub
Public Sub Class_Terminate()
m_oExcel.Quit
End Sub
Public Default Property Get Obj()
Set Obj = m_oExcel
End Property
End Class
Dim oExcel : Set oExcel = New cExcelWrapper
Dim oWBook : Set oWBook = oExcel.Obj.WorkBooks.Add()
oExcel.Obj.Visible = True
oExcel.Obj.DisplayAlerts = False
oWBook.Sheets(1).Cells(1,1) = "Div by Zero"
WScript.Echo "Check TaskManager & Enter!"
WScript.StdIn.ReadLine
WScript.Echo 1 / 0
(meant to be started with "cscript 20381749.vbs")
If you run this script with an open Taskmanager, you'll see Excel popup in the processes list (and on the screen, because of .Visible). If you then hit Enter, the script will abort with an "Division by Zero" error and the Excel process will vanish from the Processes list.
If you remove the .DisplayAlerts setting, Excel will ask you whether to save your work or not - proving thereby that the .Quit from the Class_Terminate() Sub really kicks Excel into byebye mode.
The class needs further work (basic settings, common actions (save?) before .Quit, perhaps a guard against misuse (Set oExcel = Nothing or other cargo cult crap), th .Obj addition isn't nice, and it won't help you if you kill your .vbs in a debugger, but for standard scenarios you won't see Excel zombies anymore.
Add "On Error Goto ErrorHandler" at the top of your script, and at the bottom of it, add "ErrorHandler:". Underneath the ErrorHandler label add code to manage the situation depending on the Err.Number
See Err object on MSDN.
You can also use "On Error Resume Next". Here is an example.
EDIT: My bad. "Goto" does not exist in VBS. The answer below is probably a much tidier approach.

Lotus Notes - lotusscript: shell function: illegal function call

I have a problem: I want to run a file from lotusscript code:
Dim result As Integer
result = Shell("D:\testF.dsx", 1)
And I get the following error: Illegal function call.
If I want to execute it from formula it works:
#Command([Execute]; "D:\\testF.dsx")
Thanks a lot!
I had the same problem with the shell function in lotus script with PDF files. And my workaround is to use the windows scripting host to launch the file. I am pretty sure this will solve your problem too.
Set objShell = CreateObject("WScript.Shell")
returnValue = objShell.Run("d:\testF.dsx", 3, false)enter code here
It is not possible to "Execute" a Textfile. usually there is no "run" function defined for dsx- files.
You could do it like:
Dim result as Integer
result = Shell("notepad.exe D:\testF.dsx", 1)
Or find out, which program is linked to dsx (via registry) and execute the corresponding exe with filename as Parameter. If the filename contains spaces, then it has to be enclosed:
Dim result as Integer
result = Shell({notepad.exe "D:\testF.dsx"}, 1)
And reading your last question this approach for sure is NOT the right for your request. You have to use "open" in order to process files... Like Per Hendrik told you in his response.
I had similar problems passing parameters to Outlook.
On some windows machines, this #Formula worked perfectly:
#Command([Execute]; "Outlook.exe"; "/recycle")
On Windows Terminal Servers, it caused Outlook to be unable to parse the "/recycle"
The Shell-command from LotusScript wasn't even able to locate the Outlook.exe, as it was not in the PATH.
Ralf's code helped me in this respect. The "WScript.Shell" seems able to interact with Windows registry settings. Anyway, here is the code that works for activating an open Outlook window.
Dim objShell, returnValue
Set objShell = CreateObject("WScript.Shell")
returnValue = objShell.Run("outlook.exe /recycle", 3, False)

How do I close Word (or other app) if an error occurs in a VBScript?

I wrote a VBScript app to open Word and Excel documents and search and replace blocks of text and various sections, pulling the new text from a plain text file. I purposely avoided any error checking, primarily because I couldn't figure it out at the time (and the script ran reliably anyway). Now months later on my local machine, I am inexplicably getting error messages about Normal.dot being changed and a message box asking what I want to do about it (which requires three more dialogs to finally answer). Of course this kills my ability to run the script and simply walk away, as it causes the script to fail. Currently when this happens, I have to open the Task Manager, find Winword.exe (of which the GUI isn't running) and kill it then re-run my script.
What's a reasonable way of catching the error and successfully shutting down Word (or Excel). Based on this question I'm trying this:
Set objDoc = objWord.Documents.Open(curDir1 + "\docs\template_spec.dot")
If Err.Number <> 0 Then
WScript.Echo "Error in Word Open:" & Err.Description
objWord.Quit
Else
Set objSelection = objWord.Selection
'Do replacement activities'
ReplaceText(objSelection)
objDoc.SaveAs(curDir1 + "\docs\mynewdocument.doc")
objWord.Quit
End If
Set objShell = Nothing
Set objWord = Nothing
Set objExcel = Nothing
Of course, as fate would have it, I cannot replicate the problem, so it works like normal. Does this solution seem reasonable? And a side question: How the heck do I get Word to stop complaining about Normal.dot (or get the script to handle it)? It's as if Word leaves itself open in the background after I have closed the GUI in some cases.
have you considered wrapping everything into an 'On Error Resume Next' statement so that your script ignores all the errors and continues to run as much as possible before calling the objWord.quit regardless of success or fail.
if you want more information on the correct use of 'On Error Resume Next' then go over to the msdn article on it!
Hope this helps!
Paul
I'm afraid that
WScript.Echo "..."
if it ever fires, is going to stall your script. Other than that, everything looks right. I'll play with it when I get home.
Edit: Word does hang out in the background, quite frequently. For one thing, if you use Outlook, and use Word as your Outlook editor, Word won't go away until Outlook is gone.
I'd agree with the use of "on error resume next".
If you really need to forcefully terminate Word, you can use WMI and the Win32_Process class to find and kill the process. This should be a last resort if everything else fails.
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcess = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'winword.exe'")
For Each objProcess in colProcess
objProcess.Terminate()
Next
This was a modified example from:
http://www.computerperformance.co.uk/vbscript/wmi_process_stop.htm
Also, make sure all your references to the Word automation object are closed and/or set to nothing before you terminate the process.
The most reliable way to terminate all ActiveX instances, clean up garbage, and release resources is to put the code for that purpose into Sub Class_Terminate() of a dummy class, created instance of the class allows to handle script quit event.
Option Explicit
Dim objBeforeQuitHandler, objWord
' create a dummy class instance
Set objBeforeQuitHandler = New clsBeforeQuitHandler
' create word app instance
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Add.ActiveWindow.Selection.TypeText "80040000 error was raised. About to terminate the script." & vbCrLf & "Word will be quitted without saving before script termination just you close popped up error message."
' your code here...
' raise an error
Err.Raise vbObjectError
Class clsBeforeQuitHandler
' dummy class for wrapping script quit event handler
Private Sub Class_Terminate()
Dim objDoc
On Error Resume Next ' to prevent errors in case of unexpected word app termination
If TypeName(objWord) <> "Object" Then ' word app has not been closed yet
objWord.DisplayAlerts = False
For Each objDoc In objWord.Documents
objDoc.Saved = True ' to prevent save as dialog popping up
objDoc.Close
Next
objWord.Quit
End If
End Sub
End Class

Why doesn't 'shell' work in VBscript in VS6?

In a macro for Visual Studio 6, I wanted to run an external program, so I typed:
shell("p4 open " + ActiveDocument.FullName)
Which gave me a type mismatch runtime error. What I ended up having to type was this:
Dim wshShell
Set wshShell = CreateObject("WScript.Shell")
strResult = wshShell.Run("p4 open " + ActiveDocument.FullName)
What is going on here? Is that nonsense really necessary or have I missed something?
As lassevk pointed out, VBScript is not Visual Basic.
I believe the only built in object in VBScript is the WScript object.
WScript.Echo "Hello, World!"
From the docs
The WScript object is the root object of the Windows Script Host
object model hierarchy. It never needs to be instantiated before invoking its
properties and methods, and it is always available from any script file.
Everything else must be created via the CreateObject call. Some of those objects are listed here.
The Shell object is one of the other objects that you need to create if you want to call methods on it.
One caveat, is that RegExp is sort of built in, in that you can instantiate a RegExp object like so in VBScript:
Dim r as New RegExp
VBScript isn't Visual Basic.
Give this a try:
Shell "p4 open" & ActiveDocument.FullName
VB6 uses & to concatenate strings rather than +, and you'll want to make sure the file name is encased in quotes in case of spaces. Try it like this:
Shell "p4 open """ & ActiveDocument.FullName & """"

Resources