Alias error in VBS - vbscript

How to use alias in VBScript? I am trying following code:
AliasesExample
Sub AliasesExample
Dim AliasObj
' Obtains the object that corresponds to the Notepad main window
Set AliasObj = Aliases.notepad.wndNotepad
' Checks whether the specified window exists
If AliasObj.Exists Then
' Enters text in the Notepad editor
AliasObj.Keys("Hello, world.")
Else
Log.Error("Notepad is not running.")
End If
End Sub
but getting the following error:
object required: 'Aliases'

VBScript and Windows Script Host do not support calling DLL and Windows API functions, but there're some possible solutions:
You can call DLL functions that are exposed through COM objects:
Set obj = CreateObject("Foo.Bar")
Call obj.Method(Param1, Param2)
You may be able to call some DLL functions using rundll32 if the DLL and the function meet certain requirements.
' Open "Programs and Features" using the Control_RunDLL function from shell32.dll
Set oShell = CreateObject("WScript.Shell")
oShell.Run "rundll32.exe shell32.dll Control_RunDLL appwiz.cpl,,0"
Other than that, you're out of luck.
So generally, you need a COM-callable wrapper for your DLL function to be able to use it from VBScript.

Related

Sending Mail through vbscript and attaching file using right click context menu mail not being send [duplicate]

I have this script saved in "test.vbs":
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(workFolder &"\test.txt", 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
When I run the script I want to pass the value of the "workFolder" variable.
How can I do this? Can I do it? Something like "cscript test.vbs workFolder:'C:\temp\'" perhaps?
Bonus question: Is it neccessary to clean up the passed variable with "Set workFolder = Nothing" or does VBSCript do that automatically when it terminates? Maybe "Set File = Nothing" and "Set FSO = Nothing" is unneccessary also? Please let me know if you know the answer to both these questions.
You can use WScript.Arguments to access the arguments passed to your script.
Calling the script:
cscript.exe test.vbs "C:\temp\"
Inside your script:
Set File = FSO.OpenTextFile(WScript.Arguments(0) &"\test.txt", 2, True)
Don't forget to check if there actually has been an argument passed to your script. You can do so by checking the Count property:
if WScript.Arguments.Count = 0 then
WScript.Echo "Missing parameters"
end if
If your script is over after you close the file then there is no need to set the variables to Nothing. The resources will be cleaned up automatically when the cscript.exe process terminates. Setting a variable to Nothing usually is only necessary if you explicitly want to free resources during the execution of your script. In that case, you would set variables which contain a reference to a COM object to Nothing, which would release the COM object before your script terminates. This is just a short answer to your bonus question, you will find more information in these related questions:
Is there a need to set Objects to Nothing inside VBA Functions
When must I set a variable to “Nothing” in VB6?
Inside of VBS you can access parameters with
Wscript.Arguments(0)
Wscript.Arguments(1)
and so on. The number of parameter:
Wscript.Arguments.Count
Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.
So in your code you could have:
strFolder = Wscript.Arguments.Item(0)
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.
MS Technet examples
You can also use named arguments which are optional and can be given in any order.
Set namedArguments = WScript.Arguments.Named
Here's a little helper function:
Function GetNamedArgument(ByVal argumentName, ByVal defaultValue)
If WScript.Arguments.Named.Exists(argumentName) Then
GetNamedArgument = WScript.Arguments.Named.Item(argumentName)
Else
GetNamedArgument = defaultValue
End If
End Function
Example VBS:
'[test.vbs]
testArg = GetNamedArgument("testArg", "-unknown-")
wscript.Echo now &": "& testArg
Example Usage:
test.vbs /testArg:123
To answer your bonus question, the general answer is no, you don't need to set variables to "Nothing" in short .VBS scripts like yours, that get called by Wscript or Cscript.
The reason you might do this in the middle of a longer script is to release memory back to the operating system that VB would otherwise have been holding. These days when 8GB of RAM is typical and 16GB+ relatively common, this is unlikely to produce any measurable impact, even on a huge script that has several megabytes in a single variable. At this point it's kind of a hold-over from the days where you might have been working in 1MB or 2MB of RAM.
You're correct, the moment your .VBS script completes, all of your variables get destroyed and the memory is reclaimed anyway. Setting variables to "Nothing" simply speeds up that process, and allows you to do it in the middle of a script.

Expected Statement error when using multiple parameters in VBS

I am working on making a simple vbs that will open and close an excel file and save as it closes. This is to update the values inside the excel file after they are modified by a separate python script, and I need to do it this way for many dumb reasons outside my control.
I don't have a lot of experience with VBS but what I researched about this, I don't see the error in my code. However, I get an error whenever I try to run the code below. There error is:
Line: 7
Char: 39
Error: Expected statement
Code: 800A0400
Source: Microsoft VBScript compilation error
Any help would be appreciated, thanks!
dim fso
set fso = CreateObject("Scripting.FileSystemObject")
if(fso.FileExists("C:\Users\Public\Documents\Templates\testfile.xlsx")) then
set xlapp = createobject("Excel.Application")
xlapp.Workbooks.Open "C:\Users\Public\Documents\Templates\testfile.xlsx"
xlapp.ActiveWorkbook.SaveAs Filename:="C:\Users\Public\Documents\Templates\testfile_test.xlsx", FileFormat:=51, ConflictResolution:=2
xlapp.ActiveWorkbook.Close SaveChanges:=True
end if
If you are using standalone VBS, the following lines won't work because VBS isn't VBA. VBA supports Named Argument Syntax in function calls whereas its not supported by VBS
xlapp.ActiveWorkbook.SaveAs Filename:="C:\Users\Public\Documents\Templates\testfile_test.xlsx", FileFormat:=51, ConflictResolution:=2
xlapp.ActiveWorkbook.Close SaveChanges:=True
You have to provide the arguments to the function. So Function ArgName:=ArgValue becomes Function ArgValue
xlapp.ActiveWorkbook.SaveAs "C:\Users\Public\Documents\Templates\testfile_test.xlsx",51,,,,,,2
xlapp.ActiveWorkbook.Close True

vbscript cannot find batch file stored in google drive

I am trying to run the following C:\users\jdoe\google drive\bin\script.vbs script on Windows 7:
CreateObject("Wscript.Shell").Run "C:\users\jdoe\google drive\bin\run.bat", 0, True
But I always get the error:
---------------------------
Windows Script Host
---------------------------
Script: C:\Users\jdoe\Google Drive\bin\script.vbs
Line:1
Char: 1
Error: The system cannot find the file specified.
Code: 80070002
Source: (null)
---------------------------
OK
---------------------------
When I change the path of my run.bat file to c:\run.bat and of course move the run.bat file to c:\, the script.vbs runs without problems.
Any way to get my scripts stored in google drive to run? I have the same issue when using the local group policy editor to select a shutdown or logon/logoff script that is stored in google drive...
Thanks a lot!
CreateObject("Wscript.Shell").Run "C:\users\jdoe\google drive\bin\run.bat", 0, True
^..................^ ^...............^
command to run arguments
You need to quote the the command to avoid problems with spaces
CreateObject("Wscript.Shell").Run """C:\users\jdoe\google drive\bin\run.bat""", 0, True
Remember that a double quote inside a string needs to be escaped, writting two double quotes where one must be included.
To avoid problems with spaces : you must try like this way to get rid of this error that comes from spaces in the path of your application:
Option Explicit
Dim Application
Application = "C:\users\jdoe\google drive\bin\run.bat"
Call RunThis(Application)
'*********************************************************************************
Sub RunThis(Application)
Dim Ws,Result
Set Ws = CreateObject("WScript.Shell")
Result = Ws.Run(DblQuote(Application),0,True)
End Sub
'*********************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'*********************************************************************************

ShellExecute raises type mismatch error when trying to open a file

I am trying to automate a .application file to open automatically on an end users machine. The code I found online says to do this:
Dim my_file
my_file = "c:/location/example.application"
ShellExecute 0, vbNullString, my_file, vbNullString, vbNullString, vbNormalFocus
but when I try to run it I get a type mismatch error on line 4 which is the ShellExecute line. How can I fix this?
ShellExecute() is a method of a Shell Application object. You'll need to create an instance of the class before you can call one of its methods:
Set objShell = CreateObject("Shell.Application")
objShell.ShellExecute my_file
Most of the parameters to ShellExecute() are optional and can be omitted, if you'd like.
See this page for information.
Also note that constants defined by external type libraries (as is the case here) are not immediately available to VBScript. That means your script will not understand vbNormalFocus. The easiest way to overcome this is to just define the constants yourself.
Const vbNormalFocus = 1

How to Run VBS script from cmd?

I have the following vbs script from Microsoft Support for adding Excel add-in:
Dim oXL As Object
Dim oAddin As Object
Set oXL = CreateObject("Excel.Application")
oXL.Workbooks.Add
Set oAddin = oXL.AddIns.Add("c:\Program Files\MyApp\MyAddin.xla", True)
oAddin.Installed = True
oXL.Quit
Set oXL = Nothing
I save the above script to a file called as addin.vbs and run it from a command console:
C:\...>cscript addin.vbs
I got the following error:
c:\...\addin.vbs(1, 9) Microsoft VBScript compilation error: Expected end of statement
Not sure how I can run it from cmd console?
I am running it from Windows XP.
Visual Basic for Applications (VBA, which your code is written in) and Visual Basic Scripting Edition (VBS) are not the same language.
Windows Scripting Host (WSH, i.e. cscript.exe and wscript.exe) only handles Active Scripting languages (in most installs, VBScript and JScript). VBA can only be run within the application that is destined to host it.
Just follow the directions on the Microsoft Support page you have and add the script to Excel.
The error occurs because of the As Object clause. Unlike VBA, VBScript has only one data type — Variant, so you don't specify the data type when declaring a variable. Remove the As Object clauses and the script should work fine:
Dim oXL, oAddin
Set oXL = CreateObject("Excel.Application")
oXL.Workbooks.Add
Set oAddin = oXL.AddIns.Add("c:\Program Files\MyApp\MyAddin.xla", True)
oAddin.Installed = True
oXL.Quit
Set oXL = Nothing

Resources