Expected end of statement (vbscript) - vbscript

I have a very simple vbscript code:
Dim path As String = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)
Dim executable As String = Path.Combine(path, "Google\\Chrome\\Application\\chrome.exe")
Process.Start(executable, "http://google.com")
When I execute the file, I got the following error:
Expected end of statement
What am I doing wrong?

Your code isn't VBScript, it's mostly VB.Net. You cannot declare variables with types in VBScript and you cannot assign a value to a variable while declaring it.
Here's a VBScript solution that will work:
Dim objWsc
Set objWsc = CreateObject("WScript.Shell")
Dim sPath
sPath = objWsc.ExpandEnvironmentStrings("%ProgramFiles%")
Dim sExecutable
sExecutable = """" & sPath & "\Google\Chrome\Application\chrome.exe" & """"
Dim sCommand
sCommand = sExecutable & " http:\\google.com"
objWsc.Run sCommand

Related

Long Path Problem using WScript.Arguments

In continuation of Call VBScript from Windows Explorer Context Menu, I managed to get a VBScript file running from SendTo in the Windows Explorer.
I've changed my code to copy the file that invokes the script to my Temp folder. The new problem is that if the path is over 256 characters, I can't loop through WScript.Arguments to get all of it. Is there another way to get the full path (including the file name and it's extension)?
Option Explicit
Call OpenDocuWorksFile
Sub OpenDocuWorksFile()
Const sTitle = "Open DocuWorks File"
Dim iArgumentsCount
Dim iArgument
Dim sFilePath
Dim sTempFolder
Dim oFileScriptingObject
Dim sFileName
Dim oShell
iArgumentsCount = WScript.Arguments.Count
On Error Resume Next
For iArgument = 0 To iArgumentsCount
sFilePath = sFilePath & WScript.Arguments(iArgument)
Next
On Error GoTo 0
Set oFileScriptingObject = CreateObject("Scripting.FileSystemObject")
With oFileScriptingObject
sFileName = .GetFileName(sFilePath)
sTempFolder = oFileScriptingObject.GetSpecialFolder(2) 'Temp Folder
If .GetExtensionName(sFileName) = "xdw" Then
.CopyFile sFilePath, sTempFolder & "\", True 'Overwrite
Set oShell = CreateObject("Shell.Application")
oShell.Open sTempFolder & "\" & sFileName
Else
MsgBox "Please select a DocuWorks file.(.xdw)", vbCritical, sTitle
End If
End With
Set oFileScriptingObject = Nothing
Set oShell = Nothing
End Sub

vbscript+function calling function - return value

I have a vbscript that calls a second vbscript and runs a function. This second function returns a value. But I can't figure out how to get this value, as the result of the first function returns the status code.
original call: fileCASTRING(12345678)
vbscript 1
function fileCASTRING(varRAW)
lresult = CreateObject("WScript.Shell").Run ("c:\windows\syswow64\cscript.exe C:\ERMXData\Config\query-castring.vbs " & varRAW,0,true)
fileCASTRING=1
end function
query-castring.vbs
doctype=WScript.Arguments.Item(0)
Dim strCon
strCon = "DSN=*****; " & _
"uid=*****;pwd=*****;"
Dim oCon: Set oCon = WScript.CreateObject("ADODB.Connection")
Dim oRs: Set oRs = WScript.CreateObject("ADODB.Recordset")
oCon.Open strCon
Set oRs = oCon.Execute("select ESBLINK_ADMR_CODE from ESBLINK where ESBLINK_DTYP_CODE like '%" + doctype + "%'"")
queryB=oRs.Fields(0).Value
oCon.Close
Set oRs = Nothing
Set oCon = Nothing
I have to do it like this because the program that runs vbscript 1 runs in 64 bit mode and the code in query-castring.vbs needs to run in 32bit mode in order for it to work. How can I get the queryB value back to the original caller? I am trying to not have to write the value to a file.
The only easy way to communicate between two command line processes is via StdOut.
(Be aware the code is not tested but should get you into the right direction.)
VBScript 1
Option Explicit
' ...
Function fileCASTRING(varRAW)
Dim program, script, cmdline, output
program = "c:\windows\syswow64\cscript.exe /nologo"
script = "C:\ERMXData\Config\query-castring.vbs"
cmdLine = program & " " script & " """ & varRAW & """"
output = ""
With CreateObject("WScript.Shell").Exec(cmdLine)
While Not .StdOut.AtEndOfStream
output = output & .StdOut.ReadAll
Wend
End With
fileCASTRING = output
End Function
see the documentation of the WshScriptExec object
query-castring.vbs
Option Explicit
Dim doctype: doctype = WScript.Arguments.Item(0)
Dim strCon: strCon = "DSN=*****;uid=*****;pwd=*****;"
Dim strSql: "select ESBLINK_ADMR_CODE from ESBLINK where ESBLINK_DTYP_CODE like '%' + ? + '%'"
Dim oCon: Set oCon = WScript.CreateObject("ADODB.Connection")
Dim oCmd: Set oCmd = WScript.CreateObject("ADODB.Command")
oCon.Open strCon
With WScript.CreateObject("ADODB.Command")
Set .ActiveConnection = oCon
.CommandText = strSql
.Parameters.Add(.CreateParameter)
.Parameters(0).Value = doctype
With .Execute
If Not .EOF Then
WScript.Echo .Fields("ESBLINK_ADMR_CODE").Value
End If
End With
End With
oCon.Close
See the documentation of the ADODB Command and Parameter objects. Don't build SQL from strings.
Also, look into "integrated security" connection strings - do not store plain text passwords in in code files. ADODB can easily use the security context of the account that runs the script, if you tell it to.
VBScript 1
Function getADMRCODE(varRAW)
Dim program, script, cmdline, output
program = "c:\windows\syswow64\cscript.exe /nologo"
script = "C:\ERMXData\Config\common_app\queries\admrcode.vbs"
cmdLine = program & " " & script & " """ & varRAW & """"
output = ""
With CreateObject("WScript.Shell").Exec(cmdLine)
While Not .StdOut.AtEndOfStream
output = output & .StdOut.ReadAll
Wend
End With
getADMRCODE = output
End Function
query-castring.vbs
Dim doctype: doctype = WScript.Arguments.Item(0)
Dim strCon
strCon = "DSN=*****; " & _
"uid=*****;pwd=*****;"
Dim oCon: Set oCon = WScript.CreateObject("ADODB.Connection")
Dim oRs: Set oRs = WScript.CreateObject("ADODB.Recordset")
oCon.Open strCon
Set oRs = oCon.Execute("select ESBLINK_ADMR_CODE from ESBLINK where ESBLINK_DTYP_CODE LIKE '%" + doctype + "%'")
WScript.Echo oRs.Fields(0).Value
oCon.Close
Set oRs = Nothing
Set oCon = Nothing

Path not found when running the program

This code is for updating the database, but every time I click the “start update” button, a “PATH NOT FOUND” error is shown.
Dim strEmpFileName As String
Dim strBackSlash As String
Dim intEmpFileNbr As Integer
Dim strEmpFileName1 As String
Dim strBackSlash1 As String
Dim intEmpFileNbr1 As Integer
Dim fPath As New FileSystemObject
Dim strEmpFileName2 As String
Dim strBackSlash2 As String
Dim intEmpFileNbr2 As Integer
Dim strEmpFileName21 As String
Dim strBackSlash21 As String
Dim intEmpFileNbr21 As Integer
Dim strEmpFileName21X As String
Dim strBackSlash21X As String
Dim intEmpFileNbr21X As Integer
Dim strEmpFileName21s As String
Dim strBackSlash21s As String
Dim intEmpFileNbr21s As Integer
strBackSlash = IIf(Right$(App.Path, 1) = "\", "", "\")
strEmpFileName = App.Path & strBackSlash & "\SOURCE\SWA.exe"
txtSource.Text = strEmpFileName
FileCopy txtSource.Text, "\\Mainfile\SSMS_UPDATE\SHIPS ACCOUNTING\SWA.exe"
FileCopy txtSource.Text, "C:\SANKO PROGRAM\SPECIAL WORK\SWA.exe"
Since you are already checking for a backslash in
strBackSlash = IIf(Right$(App.Path, 1) = "\", "", "\")
strEmpFileName = App.Path & strBackSlash & "\SOURCE\SWA.exe"
You should not need the backslash at the start of "\SOURCE\SWA.exe"
You are misusing the IIf function. Syntax, IIf(expr, truepart, falsepart). Your statement checks for a backslash and if the last character is "\", sets your variable to an empty string. But the false part sets the variable to "\" if it is not the last character in your path. For example, if App.Path = C:\MyApplication your IIF function would set strBackSlash = "\" and strEmpFileName will be C:\MyApplication\\SOURCE\SWA.exe.For your code you want to use a regular If statement to replace the backslash character with an empty string, then use the hard-coded backslash when you build the path.
strAppPath = App.Path
If(Right$(strAppPath, 1) = "\" Then
strAppPath = Left$(strAppPath, Len(strAppPath) - 1)
End Id
strEmpFileName = strAppPath & "\SOURCE\SWA.exe"
The full MSDN documentation is here.
Also, getting the application path is something that is done a lot. I suggest you write your own function to do this and add it to a project .bas file. Then you call the function from where ever you need it and the returned path format, (with or without the trailing backslash) is consistent. My personal function makes sure I have a trailing backslash.
Public Function AppPath() As String
Dim sAppPath As String
sAppPath = App.Path
If Right$(sAppPath, 1) <> "\" Then 'check that I'm not in the root
sAppPath = sAppPath & "\"
End If
AppPath = sAppPath
End Function
useage: strEmpFileName = AppPath() & "SOURCE\SWA.exe"

Executing VBScript file from Excel VBA macros

I need some excel vba examples, where with in the VBA code(Excel Macro) i could call a VBScript and will get some values like filename and directory information from the vbscript and assign it to the variables in VBA code.
Thank you in advance
Some thing like this
VBA macro:
Sub Foo2Script
Dim x As Long
x=2
'Call VBscript here
MsgBox scriptresult
End Sub
VBScript:
Dim x, y ,Z
x = x_from_macro
y = x + 2
Z = X+Y
scriptresult = y,Z
It can be done but I would have to agree with Tomalak and others that it's not the best way to go. However, saying that, VBScript can work wonders occasionally if you use it as a kind of fire and forget mechanism. It can be used quite effectively to simulate multi-threading in VBA whereby you breakdown the payload and farm it out to individual VBScripts to run independently. Eg you could arrange a "swarm" of individual VBScripts to mass download from websites in the background whilst VBA continues with other code.
Below is some VBA code I've simplified to show what can be done and writes a simple VBScript on the fly. Normally I prefer to run it using 'wshShell.Run """" & SFilename & """" which means I can forget about it but I've included in this example this method Set proc = wshShell.exec(strexec) which allows a test of the object for completion
Put this in MODULE1
Option Explicit
Public path As String
Sub writeVBScript()
Dim s As String, SFilename As String
Dim intFileNum As Integer, wshShell As Object, proc As Object
Dim test1 As String
Dim test2 As String
test1 = "VBScriptMsg - Test1 is this variable"
test2 = "VBScriptMsg - Test2 is that variable"
'write VBScript (Writes to Excel Sheet1!A1 & Calls Function Module1.ReturnVBScript)
s = s & "Set objExcel = GetObject( , ""Excel.Application"") " & vbCrLf
s = s & "Set objWorkbook = objExcel.Workbooks(""" & ThisWorkbook.Name & """)" & vbCrLf
s = s & "Set oShell = CreateObject(""WScript.Shell"")" & vbCrLf
s = s & "Msgbox (""" & test1 & """)" & vbCrLf
s = s & "Msgbox (""" & test2 & """)" & vbCrLf
s = s & "Set oFSO = CreateObject(""Scripting.FileSystemObject"")" & vbCrLf
s = s & "oShell.CurrentDirectory = oFSO.GetParentFolderName(Wscript.ScriptFullName)" & vbCrLf
s = s & "objWorkbook.sheets(""Sheet1"").Range(""" & "A1" & """) = oShell.CurrentDirectory" & vbCrLf
s = s & "Set objWMI = objWorkbook.Application.Run(""Module1.ReturnVBScript"", """" & oShell.CurrentDirectory & """") " & vbCrLf
s = s & "msgbox(""VBScriptMsg - "" & oShell.CurrentDirectory)" & vbCrLf
Debug.Print s
' Write VBScript file to disk
SFilename = ActiveWorkbook.path & "\TestVBScript.vbs"
intFileNum = FreeFile
Open SFilename For Output As intFileNum
Print #intFileNum, s
Close intFileNum
DoEvents
' Run VBScript file
Set wshShell = CreateObject("Wscript.Shell")
Set proc = wshShell.exec("cscript " & SFilename & "") ' run VBScript
'could also send some variable
'Set proc = wsh.Exec("cscript VBScript.vbs var1 var2") 'run VBScript passing variables
'Wait for script to end
Do While proc.Status = 0
DoEvents
Loop
MsgBox ("This is in Excel: " & Sheet1.Range("A1"))
MsgBox ("This passed from VBScript: " & path)
'wshShell.Run """" & SFilename & """"
Kill ActiveWorkbook.path & "\TestVBScript.vbs"
End Sub
Public Function ReturnVBScript(strText As String)
path = strText
End Function
This demonstrated several ways that variables can be passed around.

How to check for registry value using VbScript

How can I check for registry value using VbScript?
Function ReadFromRegistry(strRegistryKey, strDefault)
Dim WSHShell, value
On Error Resume Next
Set WSHShell = CreateObject("WScript.Shell")
value = WSHShell.RegRead( strRegistryKey )
If err.number <> 0 Then
readFromRegistry = strDefault
Else
readFromRegistry = value
End If
Set WSHShell = Nothing
End Function
Usage :
str = ReadfromRegistry("HKEY_LOCAL_MACHINE\SOFTWARE\Adobe\ESD\Install_Dir", "ha")
WScript.echo "returned " & str
Original post
Try something like this:
Dim windowsShell
Dim regValue
Set windowsShell = CreateObject("WScript.Shell")
regValue = windowsShell.RegRead("someRegKey")
This should work for you:
Dim oShell
Dim iValue
Set oShell = CreateObject("WScript.Shell")
iValue = oShell.RegRead("HKLM\SOFTWARE\SOMETHINGSOMETHING")
Try this. This script gets current logged in user's name & home directory:
On Error Resume Next
Dim objShell, strTemp
Set objShell = WScript.CreateObject("WScript.Shell")
strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERNAME"
WScript.Echo "Logged in User: " & objShell.RegRead(strTemp)
strTemp = "HKEY_CURRENT_USER\Volatile Environment\USERPROFILE"
WScript.Echo "User Home: " & objShell.RegRead(strTemp)
Set objShell = WScript.CreateObject("WScript.Shell")
skey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{9A25302D-30C0-39D9-BD6F-21E6EC160475}\"
with CreateObject("WScript.Shell")
on error resume next ' turn off error trapping
sValue = .regread(sKey) ' read attempt
bFound = (err.number = 0) ' test for success
end with
if bFound then
msgbox "exists"
else
msgbox "not exists"
End If

Resources