Need to find character within apostrophe substring and replace it, any ideas? - vbscript

Ok, let me preface this question with the fact that I am extremely new to vb script, but I need to make an addition to a script that another developer created and he is away.
Problem. :
I am getting data that is feed into a process. The script I already have handles some things that I won't go into. One thing I found out that it doesn't handle correctly is commas that occur in double quotes.
So I get some data like this. :
Joe, Bill, James, Alex, "Google, Inc", Rose, "Kickstarter, LLC"
What happens is that when this script kicks to the process application it blows up because of these commas in the double quotes. I need to be able to have this script go in and replace those commas in the Google and Kickstarter blocks with something a little more unique.
If you have the answer to this I would appreciate it, but I wouldn't mind some direction either of something that does something like this, etc.
Any answers are greatly appreciated. Again very new to vbascript just started reading syntax on it today.

You left out a few details about the format of the input data and the replacement text. However, the approach you need to take is to use the regular expression capability of VBScript to identify patterns in your input data, then use the "Replace" method to replace them. Here's a short MS article about regular expressions in VBScript.
Here's an example of what it might look like. This example is definitely NOT bullet proof and it makes some assumptions, but I think it will get you started:
Dim re, strstr, newstrstr
Dim inputstrarray(7)
Set re = new regexp
inputstrarray(0) = "Joe"
inputstrarray(1) = "Bill"
inputstrarray(2) = "James"
inputstrarray(3) = "Alex"
inputstrarray(4) = """" & "Google, Inc" & """"
inputstrarray(5) = "Rose"
inputstrarray(6) = """" & "Kickstarter, LLC" & """"
re.pattern = ",\s" 'pattern is a comma followed by a space
For Each strstr In inputstrarray 'loop through each string in the array
newstrstr = re.Replace(strstr, "_") 'replace the pattern with an underscore
If StrComp(strstr,newstrstr) Then
Wscript.Echo "Replace " & strstr & " with " & newstrstr
Else
Wscript.Echo "No Change"
End If
Next
Output looks like the following:
No Change
No Change
No Change
No Change
Replace "Google, Inc" with "Google_Inc"
No Change
Replace "Kickstarter, LLC" with "Kickstarter_LLC"
No Change

Related

Narrator Pitch on Variables in VBS

I am writing a script in VBS for when I log in I am greeted with the time. However, the XML variable for voice pitch is not functioning without text that is static. Am I missing something?
Sapi.speak "<PITCH MIDDLE = '5'/>Good Morning"
This runs at a higher pitch...
Sapi.speak minute(time)
While this is normal.
I have tried "<PITCH MIDDLE = '5'/> minute(time)", <PITCH MIDDLE = '5'/>middle(time), and "<PITCH MIDDLE = '5'/>"middle(time).
All of which return with errors.
I appreciate any help that is given. :)
What you pass to the Speak method is a string. You are trying to pass a string and a number, so, all you should need to do is to concatenate both using the & concatenate operator to obtain a string with the full content
Sapi.speak "<PITCH MIDDLE = '5'/>" & Minute(Time)

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

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:

vbscript - Replace all spaces

I have 6400+ records which I am looping through. For each of these: I check that the address is valid by testing it against something similar to what the Post Office uses (find address). I need to double check that the postcode I have pulled back matches.
The only problem is that the postcode may have been inputted in a number of different formats for example:
OP6 6YH
OP66YH
OP6 6YH.
If Replace(strPostcode," ","") = Replace(xmlAddress.selectSingleNode("//postcode").text," ","") Then
I want to remove all spaces from the string. If I do the Replace above, it removes the space for the first example but leave one for the third.
I know that I can remove these using a loop statement, but believe this will make the script run really slow as it will have to loop through 6400+ records to remove the spaces.
Is there another way?
I didn't realise you had to add -1 to remove all spaces
Replace(strPostcode," ","",1,-1)
Personally I've just done a loop like this:
Dim sLast
Do
sLast = strPostcode
strPostcode = Replace(strPostcode, " ", "")
If sLast = strPostcode Then Exit Do
Loop
However you may want to use a regular expression replace instead:
Dim re : Set re = New RegExp
re.Global = True
re.Pattern = " +" ' Match one or more spaces
WScript.Echo re.Replace("OP6 6YH.", "")
WScript.Echo re.Replace("OP6 6YH.", "")
WScript.Echo re.Replace("O P 6 6 Y H.", "")
Set re = Nothing
The output of the latter is:
D:\Development>cscript replace.vbs
OP66YH.
OP66YH.
OP66YH.
D:\Development>
This is the syntax Replace(expression, find, replacewith[, start[, count[, compare]]])
it will default to -1 for count and 1 for start. May be some dll is corrupt changing the defaults of Replace function.
String.Join("", YourString.Split({" "}, StringSplitOptions.RemoveEmptyEntries))
Because you get all strings without spaces and you join them with separator "".

VB6 getting ride of large spaces

Hey all, i am trying to replace large spaces between text with just one. My output looks like this right now:
5964215">
This is just the first example of the spaces
5964478">
This would be the 2nd example of showing how many spaces this thing has in each sentence.
5964494">
That comes from a textbox that has multi-line to true. Here is what it looks like when it doesn't have multi-line to true.
http://www.june3rdsoftware.com/forums/vb6.jpg
I can not seem to get the spaces to go away! BTW, this text is from a webpage if that makes any difference.
David
According to the suggestion of MvanGeest, here is some VB code to replace blocks of white spaces:
Sub test()
Dim x As String, y As String
x = "abcd defg 1233"
Dim re As New RegExp
re.Pattern = "\s+"
re.Global = True
y = re.Replace(x, " ")
Debug.Print y
End Sub
To make this work, you will have to add a reference to "Microsoft VBScript Regular Expresssions" to your project.
Assuming no regex support, why not set up a simple state machine that will set the state=1 when a space is found and set state=0 once a non-space is encountered. You can move char by char when state=0 (thus copying over only 1 space per series of spaces).
Also assuming no regex, you could try something like
str = "long text with spaces "
i = LenB(str)
str = Replace(str, " ", " ")
Do While LenB(str) <> i
i = LenB(str)
str = Replace(str, " ", " ")
Loop
Of course this code could be optimized for long space sequences but it might be all you need as well

Resources