How to use substring in vbscript within a xsl page - vbscript

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

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"

Is there a direct funtion to count numbers inside a string?

I have a string that contains digits inside. For example, "adf20j83n,m3jh2k9". Is there a direct way to count the number of digits inside the string. As in my example, it should give me "7" as an output.
Also, I have tried RegExp but it's not working in VBScript in QTP.
Btw, I'm not looking for loops and stuff like that. Just a direct way, or a suggestion to make this RegExp work in QTP.
You'll probably need to create the COM object via its ProgId:
Dim re
Set re = CreateObject("VBScript.RegExp")
re.Pattern = "\d"
re.Global = True
MsgBox "Digits: " & re.Execute("adf20j83n,m3jh2k9").Count
Output:
Digits: 7
I know it's techically what you said but it's a good way nonetheless
Try using this function:
Public Sub CountNumeric(ByVal input As String)
Dim numericCount As Integer = 0
For Each c As Char In input
If Char.IsDigit(c) Then numericCount += 1
Next
MessageBox.Show(String.Format("Number of numerics : {0}", numericCount)
End Sub
EDIT:
You could also try this:
Dim charColl As MatchCollection = Regex.Matches(input , "^\d+$")
Console.WriteLine(charColl.Count.ToString())

Is there a way to make special characters work when using InStr in VBScript?

A VBScript is in use to shorten the system path by replacing entries with the 8.3 versions since it gets cluttered with how much software is installed on our builds. I'm currently adding the ability to remove duplicates, but it's not working correctly.
Here is the relevant portion of code:
original = "apple;orange;apple;lemon\banana;lemon\banana"
shortArray=Split(original, ";")
shortened = shortArray(1) & ";"
For n=2 to Ubound(shortArray)
'If the shortArray element is not in in the shortened string, add it
If NOT (InStr(1, shortened, shortArray(n), 1)) THEN
shortened = shortened & ";" & shortArray(n)
ELSE
'If it already exists in the string, ignore the element
shortened=shortened
End If
Next
(Normally "original" is the system path, I'm just using fruit names to test...)
The output should be something like
apple;orange;lemon\banana
The issue is entries with punctuation, such as lemon\banana, seem to be skipped(?). I've tested it with other punctuation marks, still skips over it. Which is an issue, seeing how the system path has punctuation in every entry.
I know the basic structure works, since there are only one of each entry without punctuation. However, the real output is something like
apple;orange;lemon\banana;lemon\banana
I thought maybe it was just a character escape issue. But no. It still will not do anything with entries containing punctuation.
Is there something I am doing wrong, or is this just a "feature" of VBScript?
Thanks in advance.
This code:
original = "apple;orange;apple;lemon\banana;lemon\banana"
shortArray = Split(original, ";")
shortened = shortArray(0) ' array indices start with 0; & ";" not here
For n=1 to Ubound(shortArray)
'If the shortArray element is not in in the shortened string, add it
'i.e. If InStr() returns *number* 0; Not applied to a number will negate bitwise
' If 0 = InStr(1, shortened, shortArray(n), 1) THEN
If Not CBool(InStr(1, shortened, shortArray(n), 1)) THEN ' if you insist on Not
WScript.Echo "A", shortArray(n), shortened, InStr(1, shortened, shortArray(n), vbTextCompare)
shortened = shortened & ";" & shortArray(n)
End If
Next
WScript.Echo 0, original
WScript.Echo 1, shortened
WScript.Echo 2, Join(unique(shortArray), ";")
Function unique(a)
Dim d : Set d = CreateObject("Scripting.Dictionary")
Dim e
For Each e In a
d(e) = Empty
Next
unique = d.Keys()
End Function
output:
0 apple;orange;apple;lemon\banana;lemon\banana
1 apple;orange;lemon\banana
2 apple;orange;lemon\banana
demonstrates/explains your errors (indices, Not) and shows how to use the proper tool for uniqueness (dictionary).

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

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

Resources