What does these lines of code do in VBScript? - vbscript

I am converting them to Jython script and I felt all it does is remove spaces at ends
function test (strField)
Dim re
Set re = New RegExp
re.Pattern = "^\s*"
re.MultiLine = False
strField = re.replace(strField,"")
End Function

It uses the RegExp object in VBScript to check for whitespace \s at the start of the variable passed into the Sub / Function called strField. Once it identifies the whitespace it uses the Replace() method to remove any matched characters from the start of the string.
As #ansgar-wiechers has mentioned in the comments it is just an all whitespace implementation of the LTrim() function.
I'm assuming this is meant to be a Function though (haven't tested but maybe VBScript accepts Fun as shorthand for Function, not something I'm familiar with personally) with that in mind it should return the modified strField value as the result of the function. Would also recommend using ByVal to stop the strField value after it is manipulated bleeding out of the function.
Function test(ByVal strField)
Dim re
Set re = New RegExp
re.Pattern = "^\s*"
re.MultiLine = False
strField = re.replace(strField,"")
test = strField
End Function
Usage in code:
Dim testin: testin = " some whitespace here"
Dim testout: testout = test(testin)
WScript.Echo """" & testin & """"
WScript.Echo """" & testout & """"
Output:
" some whitespace here"
"some whitespace here"

Related

How to find a file using a pattern?

I have a script that is supposed to grab a file from a folder and attach it to an email.
The code runs but nothing happens. I assume it's because strLocation is empty.
Here is an example of the file path I am trying to grab:
"C:\Users\MChambers\Desktop\Pricing Reports\Pricing_Report_201908121239 Formatted.xlsx"
Option Explicit
Const olMailItem = 0
Function FindFirstFile(strDirPath, strPattern)
Dim strResult
Dim objRegExp, objMatches
Set objRegExp = New RegExp
objRegExp.Pattern = strPattern
objRegExp.IgnoreCase = True
Dim objFso, objFolder, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strDirPath)
For Each objFile in objFolder.Files
Set objMatches = objRegExp.Execute(objFile.Name)
If objMatches.Count > 0 Then
strResult = objMatches(0).Value
Exit For
End If
Next
If Len(strResult) > 0 Then
If Right(strDirPath, 1) <> "\" Then strDirPath = strDirPath & "\"
strResult = strDirPath & strResult
End If
FindFirstFile = strResult
End Function
Sub SendBasicEmail()
Dim olApp: Set olApp = CreateObject("Outlook.Application")
Dim olEmail: Set olEmail = olApp.CreateItem(olMailItem)
Dim strLocation
Dim strPattern
strPattern = "Pricing_Report_*Formatted.xlsx"
strLocation = FindFirstFile("C:\Users\MChambers\Desktop\Pricing Reports\", strPattern)
If strLocation <> "" Then
With olEmail
.SentOnBehalfOfName = "genericemail"
.Attachments.Add (strLocation)
.To = "myemail"
.Subject = "Subject"
.Send
End With
End If
End Sub
SendBasicEmail
Update: The solution below was correct. In addition, I had to call the sub directly at the end of the file which I have updated in the code above.
The pattern you're using doesn't do what you apparently think it does.
strPattern = "Pricing_Report_*Formatted.xlsx"
You seem to expect the above to do a wildcard match (i.e. "Pricing_Report_" followed by any amount of text and "Formatted.xlsx"). That is not how regular expressions work. * in a regular expression means "zero or more times the preceding expression". The character . also has a special meaning in regular expressions, which is "any character except line-feed. Because of that your pattern would actually match the string "Pricing_Report" followed by any number of consecutive underscores, the string "Formatted", any single character except line-feed, and the string "xlsx".
Change the pattern to this
strPattern = "Pricing_Report_.*Formatted\.xlsx"
and the code will do what you want.
For further information about regular expressions in VBScript see here.

Remove unnecessary data/Spaces in CSV

I need help on how to remove spaces/emtpy in data without compromising spaces on other data. Here's my sample data.
12345," ","abcde fgh",2017-06-06,09:00,AM," ", US
expected output:
12345,,"abcde fgh",2017-06-06,09:00,AM,, US
since " " should be considered as null.
I tried the Trim() function but it did not work. I also tried Regex pattern but still no use.
Here's my sample function.
Private Sub Transform(delimiter As String)
Dim sFullPath As String
Dim strBuff As String
Dim re As RegExp
Dim matches As Object
Dim m As Variant
If delimiter <> "," Then
strBuff = Replace(strBuff, delimiter, ",")
Else
With re
.Pattern = "(?!\B""[^""]*)" & delimiter & "(?![^""]*""\B)"
.IgnoreCase = False
.Global = True
End With
Set matches = re.Execute(strBuff)
For Each m In matches
strBuff = re.Replace(strBuff, ",")
Next
Set re = Nothing
Set matches = Nothing
End If
End Sub
I think you're on the right track. Try using this for your regular expression. The two double quotes in a row are how a single double quote is included in a string literal. Some people prefer to use Chr(34) to include double quotes inside a string.
\B(\s)(?!(?:[^""]*""[^""]*"")*[^""]*$)
Using that expression on your example string
12345," ","abcde fgh",2017-06-06,09:00,AM," ", US
yields
12345,"","abcde fgh",2017-06-06,09:00,AM,"", US
Example function
Private Function Transform(ByVal strLine As String) As String
Dim objRegEx As RegExp
On Error GoTo ErrTransForm
Set objRegEx = New RegExp
With objRegEx
.Pattern = "\B(\s)(?!(?:[^""]*""[^""]*"")*[^""]*$)"
.IgnoreCase = False
.Global = True
Transform = .Replace(strLine, "")
End With
ExitTransForm:
If Not objRegEx Is Nothing Then
Set objRegEx = Nothing
End If
Exit Function
ErrTransForm:
'error handling code here
GoTo ExitTransForm
End Function
And credit where credit is due. I used this answer, Regex Replace Whitespaces between single quotes as the basis for the expression here.
I would add an output string variable and have a conditional statement saying if the input is not empty, add it on to the output string. For example (VB console app format with the user being prompted to enter many inputs):
Dim input As String
Dim output As String
Do
input = console.ReadLine()
If Not input = " " Then
output += input
End If
Loop Until (end condition)
Console.WriteLine(output)
You can throw any inputs you don't want into the conditional to remove them from the output.
Your CSV file isn't correctly formatted.
Double quote shouldn't exists, then open your CSV with Notepad and replace them with a null string.
After this, you now have a real CSV file that you can import whitout problems.

Reading and storing cyrillic in variables

I am trying to read cyrillic values separated by ; from a file, scan every line for match in the first value and assign the following values to variables.
Here is the code I have so far:
Dim objStream, strData, splitted
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("C:\temp\textfile.txt")
strData = objStream.ReadText()
MsgBox strData
splitted = split(strData, ";")
textfile.txt contains something like this:
Име;Адрес;Телефон;
Име2;Адрес2;Телефон2;
I will have a variable like this:
searchFor = "Име"
and the script must assign Адрес and Телефон to variables.
Basically, I need to search for the name(Име or Име2) in every line from the textfile and then assign the second and the third values of that line to variables.
Currently strData gets the data but it's stored as a string that I cannot manipulate or don't know how.
First split the text at newlines, then split each line at semicolons, then check if the first field matches your search value. Example:
searchFor = "Име"
For Each line In Split(strData, vbNewLine)
fields = split(line, ";")
If fields(0) = searchFor Then
varA = fields(1)
varB = fields(2)
End If
Next
Note that you must save the script in Unicode format, lest your search string be botched.
Here is the complete final working script (Thanks to Ansgar Wiechers!)
Dim objStream, strData, fields
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("C:\temp\textfile.txt")
strData = objStream.ReadText()
MsgBox strData
searchFor = "Име"
MsgBox searchFor
For Each line In Split(strData, vbNewLine)
fields = Split(line, ";")
If fields(0) = searchFor Then
varA = fields(1)
varB = fields(2)
End If
Next

String between a line

By some google resources I could write a program to extract the string between two specific strings. I could not print value or store the value into a variable using regular expressions. Here is my code.
prgName = InStr(vText, "Program")
sub_prgName = Mid(vText, prgName, 100)
MsgBox sub_prgName, vbInformation
Dim RegEx: Set RegEx = New RegExp
RegEx.IgnoreCase = True
RegEx.Pattern = "Program(.*)?Variant"
Set RegEx = RegEx.Execute(prgName)
MsgBox RegEx.Value, vbInformation
I want to get the string b/w Program and Variant. When try to see the output it says
Run time error 438, object doesn't support this property.
This is the value that I want to parse using RegEx:
Program
sqlplus $SOPS_MIPO_USER/$SOPS_MIPO_PASSWORD#$DB_SID #mipo_pruning.sql
Variant
When in doubt, read the documentation. The Execute method returns a Matches collection, so you need to iterate over that collection to get the desired result (in your case the first submatch).
For Each m In RegEx.Execute(prgName)
MsgBox m.SubMatches(0), vbInformation
Next
Demonstration:
>>> s = "Program sqlplus $SOPS_MIPO_USER/$SOPS_MIPO_PASSWORD#$DB_SID #mipo_pruning.sql Variant N/A"
>>> Set re = New RegExp
>>> re.Pattern = "Program(.*)?Variant"
>>> re.IgnoreCase = True
>>> For Each m In re.Execute(s) : WScript.Echo m.SubMatches(0) : Next
sqlplus $SOPS_MIPO_USER/$SOPS_MIPO_PASSWORD#$DB_SID #mipo_pruning.sql
Theoretically you could also do this without the loop:
Set m = RegEx.Execute(prgName)(0)
MsgBox m.SubMatches(0), vbInformation
However, RegEx.Execute(prgName)(0) would raise an error if the regular expression didn't find a match, so evaluating the results in a loop is the safer approach.
I'd remove the ? in your regular expression, though, because it'll make the group optional, so you're not guaranteed to have a SubMatches(0) item. Simply use Program(.*)Variant instead. If there's no text between "Program" and "Variant" you'll get a zero-length string as the first submatch. Or you could put it inside the parentheses right after the asterisk (Program(.*?)Variant) to make the match non-greedy (shortest match instead of longest match).
If your input string contains newlines you need to use [\s\S] instead of ., because the dot in regular expressions matches any character except newlines.
Demonstration:
>>> s = "Program" & vbNewLine & vbNewLine _
& "sqlplus $SOPS_MIPO_USER/$SOPS_MIPO_PASSWORD#$DB_SID #mipo_pruning.sql" _
& vbNewLine & vbNewLine & "Variant"
>>> WScript.Echo s
Program
sqlplus $SOPS_MIPO_USER/$SOPS_MIPO_PASSWORD#$DB_SID #mipo_pruning.sql
Variant
>>> Set re = New RegExp
>>> re.Pattern = "Program(.*)?Variant"
>>> re.IgnoreCase = True
>>> For Each m In re.Execute(s) : WScript.Echo m.SubMatches(0) : Next
>>> re.Pattern = "Program([\s\S]*)?Variant"
>>> For Each m In re.Execute(s) : WScript.Echo m.SubMatches(0) : Next
sqlplus $SOPS_MIPO_USER/$SOPS_MIPO_PASSWORD#$DB_SID #mipo_pruning.sql
As a side note, you shouldn't replace your regular expression object with the result of the Execute method.
Set RegEx = RegEx.Execute(prgName) '<-- NEVER do this!
Re-using variables is a no-no, so don't do it.
.Execute returns a collection of Match objects. This collection has a .Count but no .Value property. You can use MsgBox RegEx(0).Value to get the .Value of the first match.
Evidence:
>> sInp = "XXXProgramYYYVariantZZZ"
>> Set r = New RegExp
>> r.Pattern = "Program(.*?)Variant"
>> WScript.Echo r.Execute(sInp)(0).Value
>> WScript.Echo r.Execute(sInp)(0).SubMatches(0)
>>
ProgramYYYVariant
YYY
You should publish your input(s) and expected result(s).

Vbs script to add space if it finds a string like abc11adv to abc11 adv

Hi I am novice in vbs script. I have one text file every line has statements like
minis1in use by bla bla
rit34in use by someone
atp34in use by someone2
I want a vbs script to convert this text file to
minis1 in use by bla bla
rit34 in use by someone
atp34 in use by someone2
I found one vbs script but it replaces string at particular position in every line. But I want to search for a number only in first string in every line and number may be one digit or two digit or three digit after that number it should give space. Without replacing character with a space.
StrFileName = "C:\Users\Desktop\Scheduled\output.txt"
Const ForReading = 1
Const ForWriting = 2
Dim objFSO
Dim objTF
Dim objRexex
Dim StrFileName
Dim strTxt
StrFileName = "C:\Users\Desktop\Scheduled\output.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTF = objFSO.OpenTextFile(StrFileName, ForReading)
Set objregex = CreateObject("vbscript.regexp")
strTxt = objTF.ReadAll
objTF.Close
With objregex
.Global = True
.MultiLine = True
.Pattern = "^(.{6})[^-](.*)$"
strTxt = .Replace(strTxt, "$1" & " " & "$2")
End With
Set objTF = objFSO.OpenTextFile(StrFileName, ForWriting)
objTF.Write strTxt
objTF.Close
Maybe the pattern "^(\w+)(\d+)(\w+)" used non-globally will do what you want:
Option Explicit
Dim r : Set r = New RegExp
r.Global = False ' just the first
r.Pattern = "^(\w+)(\d+)(\w+)"
Dim s
For Each s In Split("minis1in use by+rit34adv use+atp34in use not34in use+not here1in use", "+")
WScript.Echo s
WScript.Echo r.Replace(s, "$1$2 $3")
WScript.Echo
Next
output:
cscript 25228592.vbs
minis1in use by
minis1 in use by
rit34adv use
rit34 adv use
atp34in use not34in use
atp34 in use not34in use
not here1in use
not here1in use
If "every line has statements like" what you've shown, and you're sure of that, make it easy on yourself:
strTxt = Replace(strTxt, "in use by ", " in use by ")

Resources