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

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"

Related

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:

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).

Vb6 .text property for textbox required

I am trying to convert letters to numbers.
I have a sub which ensures only numbers are put into the textbox.
My questions is will the following code work. I have a textbox(for numbers) and combobbox(for letters)
Dim sha As String
Dim stringposition As Long
Dim EngNumber As Long
sha = "abcdefghifjklmnopqrstuvwxyz"
stringposition = InStr(1, sha, Mid(1, cmbEngletter.Text, 1))
MsgBox "stringposition"
EngNumber = (txtManuNo.Text * 10) + stringposition
My only question above would be will the multiplication work with a .text. I believe it won't because it is a string. Please advise then on how to deal with a situation.
You can use CLng() to convert a string to a Long variable
CLng() will throw an error though if it doesn't like the contents of the string (for example if it contains a non-numeric character), so only use it when you are certain your string will only contain numbers
More forgiving is it to use Val() to convert a string into a numeric variable (a Double by default)
I also suggest you look into the following functions:
Asc() : returns the ASCII value of a character
Chr$() : coverts an ASCII value into a character
Left$() : returns the first characters of a string
CStr() : convert a number into a string
I think in your code you mean to show the contents of your variable stringposition instead of the word "stringposition", so you should remove the ""
I do wonder though what you are trying to accomplish with your code, but applying the above to your code gives:
Dim sha As String
Dim stringposition As Long
Dim EngNumber As Long
sha = "abcdefghifjklmnopqrstuvwxyz"
stringposition = InStr(1, sha, Left$(cmbEngletter.Text, 1))
MsgBox CStr(stringposition)
EngNumber = (Val(txtManuNo.Text) * 10) + stringposition
I used Val() because I am not certain your txtManuNo will contain only numbers
To ensure an user can only enter numbers you can use the following code:
Private Sub txtManuNo_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case vbKeyBack
'allowe backspace
Case vbKey0 To vbKey9
'allow numbers
Case Else
'refuse any other input
KeyAscii = 0
End Select
End Sub
An user can still input non-numeric charcters with other methods though, like copy-paste via mouse actions, but it is a quick and easy first filter

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

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