Assigned the key to variable and pass variable as key in vbs - vbscript

Option Explicit
Dim objShell, intRetVal, intErrNum
Dim sn As String
Set objShell = CreateObject("WScript.Shell")
objShell.Run("c:\Windows\System32\notepad.exe")
WScript.Sleep 2000
sn = f
If objShell.AppActivate("Untitled - Notepad") Then
WScript.Sleep 500
objShell.SendKeys "%{sn}"
End If
In the above vbs code I am trying to pass alt+f Key to "untitled - Notepad" application but instead of passing key directly I wanted to assigned it to some variable and then pass the variable.
But above code is throwing below error while executing the script,
E:\vbs\test2.vbs(3, 8) Microsoft VBScript compilation error: Expec
ted end of statement
How should I assigned the key to variable and pass variable as key.

There are 3 mistakes in your script:
Dim sn As String
As Adrien Lacroix already pointed out, VBScript doesn't support typed variable declarations as VBA does. Change that line into this:
Dim sn
sn = f
You want to assign the character f to the variable sn, so you have to make the former an actual string by putting it between double quotes:
sn = "f"
objShell.SendKeys "%{sn}"
VBScript doesn't support variable expansion inside strings. If you want to build a strings with values from variables you have to concatenate the variable with the string literals. Also, the curly braces are for generating special keystrokes (e.g. {Right} for → or {F10} for F10), not for variable expansion. See the documentation for details. To send Alt+F you need the following:
objShell.SendKeys "%" & sn

I think your error is on this line (E:\vbs\test2.vbs(3, 8)) :
sn = f
provoked by this one :
Dim sn As String
From MSDN :
"In VBScript, variables are always of one fundamental data type, Variant"
VBScript does not support data types as such so remove all data types from your declarations.
For example, that line should be just:
Dim sn

Related

Opening chrome browser with disabled websecurity [duplicate]

I want to insert an if statement in a cell through vba which includes double quotes.
Here is my code:
Worksheets("Sheet1").Range("A1").Value = "=IF(Sheet1!B1=0,"",Sheet1!B1)"
Due to double quotes I am having issues with inserting the string. How do I handle double quotes?
I find the easiest way is to double up on the quotes to handle a quote.
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)"
Some people like to use CHR(34)*:
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.
Another work-around is to construct a string with a temporary substitute character. Then you can use REPLACE to change each temp character to the double quote. I use tilde as the temporary substitute character.
Here is an example from a project I have been working on. This is a little utility routine to repair a very complicated formula if/when the cell gets stepped on accidentally. It is a difficult formula to enter into a cell, but this little utility fixes it instantly.
Sub RepairFormula()
Dim FormulaString As String
FormulaString = "=MID(CELL(~filename~,$A$1),FIND(~[~,CELL(~filename~,$A$1))+1,FIND(~]~, CELL(~filename~,$A$1))-FIND(~[~,CELL(~filename~,$A$1))-1)"
FormulaString = Replace(FormulaString, Chr(126), Chr(34)) 'this replaces every instance of the tilde with a double quote.
Range("WorkbookFileName").Formula = FormulaString
This is really just a simple programming trick, but it makes entering the formula in your VBA code pretty easy.
All double quotes inside double quotes which suround the string must be changed doubled. As example I had one of json file strings : "delivery": "Standard",
In Vba Editor I changed it into """delivery"": ""Standard""," and everythig works correctly. If you have to insert a lot of similar strings, my proposal first, insert them all between "" , then with VBA editor replace " inside into "". If you will do mistake, VBA editor shows this line in red and you will correct this error.
I have written a small routine which copies formula from a cell to clipboard which one can easily paste in Visual Basic Editor.
Public Sub CopyExcelFormulaInVBAFormat()
Dim strFormula As String
Dim objDataObj As Object
'\Check that single cell is selected!
If Selection.Cells.Count > 1 Then
MsgBox "Select single cell only!", vbCritical
Exit Sub
End If
'Check if we are not on a blank cell!
If Len(ActiveCell.Formula) = 0 Then
MsgBox "No Formula To Copy!", vbCritical
Exit Sub
End If
'Add quotes as required in VBE
strFormula = Chr(34) & Replace(ActiveCell.Formula, Chr(34), Chr(34) & Chr(34)) & Chr(34)
'This is ClsID of MSFORMS Data Object
Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
objDataObj.SetText strFormula, 1
objDataObj.PutInClipboard
MsgBox "VBA Format formula copied to Clipboard!", vbInformation
Set objDataObj = Nothing
End Sub
It is originally posted on Chandoo.org forums' Vault Section.
In case the comment by gicalle ever dies:
I prefer creating a global variable:
Public Const vbDoubleQuote As String = """" 'represents 1 double quote (")
Public Const vbSingleQuote As String = "'" 'represents 1 single quote (')
and using it like so:
Shell "explorer.exe " & vbDoubleQuote & sPath & vbDoubleQuote, vbNormalFocus

keeping leading zeros and keeping variable as text value instead of numeric

I've got the following VBScript code:
WScript.Echo findUser(strUser)
It calls the function: findUser. It works fine however, when the value of strUser is a value like 0001 then for some reason the function strips the zeros and returns only 0 and hence the findUser function returns error saying user not found.
Any idea how I can make sure it does not strip any characters? For some reason it is being treated as a numeric value but seeing as user account may not always have numbers only, i would prefer it treats the value of strUser as a text string
* UDPATE *
The rest of the code of how I am getting the strUser variable is below. It's getting the strUser from a CSV file. However, even if I set the strUser like this:
strUser = 0001
it still returns as an interger and removes the leading zeros.
Set oConnection = CreateObject("adodb.connection")
Set oRecordSet = CreateObject("adodb.recordset")
oConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & sCSVFileLocation & ";Extended Properties=""text;HDR=NO;FMT=Delimited"""
oRecordSet.Open "SELECT * FROM " & sCSVFile, oConnection
Do Until oRecordSet.EOF
strUser = oRecordSet.Fields.Item(0).value
WScript.Echo findUser(strUser)
On Error Resume Next
oRecordSet.MoveNext
Loop
If the numbers are listed with leading zeroes in your CSV, but end up as plain integers in your code they most likely are not in double quotes.
ID,...
0001,...
0002,...
As #Lankymart suspected the JET engine interprets numbers as numbers unless they're explicitly defined as strings by putting them in quotes:
ID,...
"0001",...
"0002",...
The preferred solution would be to fix the CSV or the process creating the CSV, so that string values are properly defined.
If that isn't possible/feasible for some reason the canonical way to turn an integer into a string with leading zeroes is to prepend the number with an all-zeroes string and cut the result string to the right length:
i = 1
s = Right("0000" & i, 4) 's = "0001"

Can a variable act as a space in VBS?

I'm teaching myself VBS and I decided to write a message encryption program. It uses the left and right functions in a loop to read every individual character.
DO
wscript.sleep 100
if Az=0 then
EXIT DO
end if
CR=right(message,aZ)
DEL=left(CR,1)
aZ=aZ-1
zZ=zZ+1
supra=""
supra="supra"
CALL KEYCOUNT
CD=left(keyword,zZ)
TAC=right(CD,1)
....
From there, it sets every character equal to a different letter based on an encryption keyword and moves onto the next character. My problem is I don't know how to deal with spaces in the message. Is there a way to make a variable have the value of a space? I've tried:
set var=space(1)
set var="&"" ""&"
set var=""
set var=" "
set var=""" """
I'm certain there are things I'm not thinking of
Thanks
Joseph
set statement assigns an object reference to a variable or property, or associates a procedure reference with an event. That isn't our case.
var=space(1) ' var contains one space character
var="&"" ""&" ' var contains &" "&
var="" ' var contains a string of zero length
var=" " ' var contains one space character
var=""" """ ' var contains " "
Or, if you would like, declare a constant for use in place of literal value of space (anywhere in your script) as follows:
Const vbSp=" "
Constants are public by default. Within procedures, constants are always private; their visibility can't be changed. Within a script, the default visibility of a script-level constant can be changed using the Private keyword. There are variations:
Private Const vbSp=" "
Public Const vbSp=" "
The problem is that you use Set (cf. here) when assigning a simple/non-object value to a variable. If you loose it, your experimental statements will 'work' (compile & run without error). Look at the output and you'll see that
var = " "
is the correct and most efficient way to assign a (string containing one) space to a variable.

VBS Script to adapt in another language

I have a script that works perfectly fine on english-based computers but does not once in another language.
The script gets the Recovery Key for Bitlocker of a Machine and then backs it up into Active Directory.
I've identified that I need to update the "Numerical Password" into the value in my corresponding language but this does not change the output of a blank variable NumericalKeyID in the end...
Option Explicit
Dim strNumericalKeyID
Dim strManageBDE,strManageBDE2
Dim oShell
Dim StrPath
Dim StdOut, strCommand
Dim Result, TPM, strLine
Dim Flag, NumericalKeyID
Set oShell = CreateObject("WSCript.Shell")
'====================================================================================
'This section looks for the Bitlocker Key Numerical ID
strManageBDE = "Manage-BDE.exe -protectors -get c:" 'Bitlocker command to gather the ID
Flag = False
Set Result = oShell.Exec(strManageBDE)'sees the results and places it in Result
Set TPM = Result.StdOut 'Sets the variable TPM to the output if the strManageBDe command
While Not TPM.AtEndOfStream
strLine = TPM.ReadLine 'Sets strLine
If InStr(strLine, "Numerical Password:") Then ' This section looks for the Numerical Password
Flag = True
End If
If Flag = True Then
If InStr(strLine, "ID:") Then 'This section looks for the ID
NumericalKeyID = Trim(strLine)' This section trims the empty spaces from the ID {} line
NumericalKeyID = Right(NumericalKeyID, Len(NumericalKeyID)-4)
Flag = False 'Stops the other lines from being collected
End If
End If
Wend
strManageBDE2 = "Manage-BDE.exe -protectors -adbackup C: -ID " & NumericalKeyID
oShell.Run strManageBDE2, 0, True 'Runs the Manage-bde command to move the numerical ID to AD.
I'm sure this is pretty dumb but my script knowledge is quite new.
Thank you a lot ! :)
In English the output of manage-bde:
Much as I hate to suggest a solution using regular expressions (Obligatory XKCD link)
I think it might be your best option here
Something like this should do the trick
.*ID:.*{(.*)}.*
To break it down for you
.* - Match any character
ID: - Match ID:
.* - Match any character
{ - match {
( - remember anything between this and the next )
} - match }
.* - Match any character
If you're not familiar with VBScript's support for regular expressions this link is pretty good Regular Expression - VBScript
Dim myRegExp, myMatches id
Set myRegExp = New RegExp
myRegExp.Global = True
myRegExp.Pattern = ".*ID:.*{(.*)}.*"
Set myMatches = myRegExp.Execute(subjectString)
id = myMatches(0).SubMatches(0)
A caveat with this solution
You might need to tweak the regular expression if the output varies a lot from machine to machine (do you ever have more than one protector?)
If you're new to Regex Expresso is a useful tool for testing/learning
Thank you David.
I only have one protector to backup, and also one drive.
The thing is, as I said, everything works perfectly when the language of the computer is in english but as soons as I have a language that replace the "Numerical Password" with some words with special characters like "é" "ñ" it will not be recognized and the variable will get a blank value.
Maybe it is because vbscript this way does not handle unicode.
To illustrate my sayings, here is a screenshot of the same screen than in my first post, but in french:

How to use substring in vbscript within a xsl page

I am trying to replace the double quotes in a string with a single quote, got the following code but get error message saying "Object Required strLocation"
Sub UpdateAdvancedDecisions(strLocation)
Dim d
Dim strLLength
strLLength = Len(strLocation) - 1
For d = 0 To strLLength
alert strLocation
strValue = strLocation.Substring(2,3)
If strLocation.substring(d,d+1)=" " " Then
strLLength = strLLength.substring(0, d) + "'" + strLLength.substring(d + 1,strLLength.length)
Next
End Sub
As Helen said, you want to use Replace, but her example assigned the result to your weird strLLength variable. Try this instead:
strLocation = Replace(strLocation, """", "'")
This one line does the job you asked about and avoids all the code currently in your given subroutine.
Other things that are problems in the code you posted:
a variable holding a number like the length of a string would not have a "str" prefix, so strLLength is misleading
strings in VBScript are indexed from 1 through length, not 0 through length-1
there is no "alert" keyword in VBScript
you assign a value to strValue, then never use it again
you need to use Mid to get a substring, there is no "substring" string method in VBScript
c = Mid(strLocation, d, 1) ' gets one character at position d
The more I look at this, the more clear it is that its some JavaScript that you're trying to run as VBScript but are not translating at all correctly.
Use a reference for VBScript like one of the following:
MSDN Library: VBScript Language Reference
W3Schools VBScript Tutorial

Resources