Find and replace a string with double quotation marks, comma and colon - excel

I'm trying to find and replace a string with double quotation marks, a comma and a colon, but I'm getting a error, I thought it was easier then it looks, but sadly I'm wrong.
What I tried so far is:
Cells.Replace What:=""Gorilla": "",", Replacement:=""Gorilla": """, LookAt:=xlPart
So the word/string I want to replace is "Gorilla": "",
The expected outcome should be "Gorilla": "" The difference is this one is (without comma)
EDIT: (to make my question more clear)
*The yellow and green highlighted parts mean nothing and is just for example purposes.
*Everything happens in column A, column D is just for example purposes.
The data looks like this in the screenshot. I have to search for the exact same string "Gorilla": "", to replace it with "Gorilla": "".
There isn't really an order in which row this part "Gorilla": "" can be, it can be on any row, but the string stays the same.

Assuming the start and end characters of your target string is always double quotes, then this custom function should work. You could include this in your macro if it's part of some other procedure.
Function fixString(theString As String) As String
Const startText As String = """"
Const endText As String = """"
Dim startPlace As Long, endPlace As Long
startPlace = InStr(1, theString, startText)
endPlace = InStrRev(theString, endText, -1)
fixString = Mid(theString, startPlace, endPlace)
End Function

Solution provided by: #chris neilsen
Solution:
What:="""Gorilla"": """",", Replacement:="""Gorilla"": """""
Solution in code:
Cells.Replace What:="""Gorilla"": """",", Replacement:="""Gorilla"": """"", LookAt:=xlPart

Related

Custom number (price) format independent of localization

I am wondering is it possible to have custom number format using Excel formula that will not be dependent on localization of Excel application (EU/US)?
For example I have value 1291660.
Then using formula =TEXT(A1;"# ##0,00"). I get as an output 1 291 660,00. The target is to have in any case 1.291.660,00 as an output. Any Excel professional to give an advice?
I have tried =TEXT(A1;"#.##0,00") - This didn't work
I think VBA is the only solution to this. I have found my old question about the same topic, but it seems that solution provided is not working for some reason?
Ultimate 1000 separator using VBA
Function CustomFormat(InputValue As Double) As String
Dim sThousandsSep As String
Dim sDecimalSep As String
Dim sFormat As String
sThousandsSep = Application.International(xlThousandsSeparator)
sDecimalSep = Application.International(xlDecimalSeparator)
' Up to 6 decimal places
sFormat = "#" & sThousandsSep & "###" & sDecimalSep & "######"
CustomFormat = Format(InputValue, sFormat)
If (Right$(CustomFormat, 1) = sDecimalSep) Then
CustomFormat = Left$(CustomFormat, Len(CustomFormat) - 1)
End If
' Replace the thousands separator with a space
' or any other character
CustomFormat = Replace(CustomFormat, sThousandsSep, " ")
End Function
By replacing CustomFormat = Replace(CustomFormat, sThousandsSep, " ") with CustomFormat = Replace(CustomFormat, sThousandsSep, ".") output is .1 291 660
You may use:
=SUBSTITUTE(SUBSTITUTE(FIXED(A1,2,0),",","."),".",",",INT(LEN(A1)/3)+1)
The way it works is that on an EU-system FIXED() will return: 1.291.660,00 but on an US-system it should return 1,291,660.00. To create the same output-string, we can SUBSTITUTE() all comma's to dots. A 2nd SUBSTITUTE() will then replace only the last dot back to a comma. To find the right index I used INT(LEN(A1)/3)+1 which works well on itegers like 1291660. If you happen to have decimal values, you can change this to:
=SUBSTITUTE(SUBSTITUTE(FIXED(A1,2,0),",","."),".",",",INT(LEN(INT(A1))/3)+1)
EDIT:
The above should always return the desired format, but it's a string. To return the numeric value in any further calculations, you can use NUMBERVALUE():
=NUMBERVALUE(C1,",",".")
Go to excel file tab, click options and then the following options as desired
Uncheck use system separators and define your own
You don't need VBA for this. You can use SUBSTITUTE to replace the default separator characters, and you can detect what these are by cutting them out from the formatted string of a known number. I use ASCII 1 (SOH) character to avoid replacing twice (e.g. replacing thousands separator from " " to ".", than replacing decimal separators from "." to "," would cause that thousands separators appear as ","):
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(TEXT(1234567.89,"# ##0.000"),MID(TEXT("# ##0",1000),2,1),CHAR(1)&" "),MID(TEXT("0.0",0.1),2,1),CHAR(1)&","),CHAR(1)&" ","."),CHAR(1)&",",",")
This will output "1.234.567,890".
This output will appear as a string (you cannot add numbers to it, and it is left adjusted by default), and you cannot change this behavior if you don't use Excels local settings for separators.
BTW, using " " for thousands separator and either "." or "," for decimals is the clearest way of displaying numbers.

Issues with Range.FormulaLocal and textstring in formula

When I finally had figured out that I can use my own language with Range.FormulaLocal in stead of Range.Formula I was very excited!
The possibilities are endless. But, I am encountering a problem with textstrings in formulas.
This code works just fine:
Range("I5").FormulaLocal = "=ALS(A5=1;H5;0)"
But these codelines are not working:
Range("I5").FormulaLocal = "=ALS(A5="x";H5;0)"
Range("I6").FormulaLocal = "=ALS.FOUT(VERT.ZOEKEN(A2;'betaaltermijnen.xlsx'!tabel;3;ONWAAR);"")
Could somebody help me?
You're accidentally ending your strings early...
First line:
If you have a variable x which you want to include in the string, then use &
Range("I5").FormulaLocal = "=ALS(A5=" & x & ";H5;0)"
If instead you're trying to have the string "x" then you must use an additional quotation mark before each in-string quotation mark. This is called an escape character.
Range("I5").FormulaLocal = "=ALS(A5=""x"";H5;0)"
This way, when VBA sees "", it treats it as the start or end of a quote within a string
By the same reasoning, your second line becomes
Range("I6").FormulaLocal = _
"=ALS.FOUT(VERT.ZOEKEN(A2;'betaaltermijnen.xlsx'!tabel;3;ONWAAR);"" "") "
Where I've used the _ underscore to continue the line without it getting too long, because the last 6 characters are the important bit!

Pass string into Range Function in VBA

I am trying to create a range in a function but the range varies so I am going to pass in the definition as a string but I am running into an error because it says it "Expected an array". So, I thought this was because the double quotes weren't included so I tried to include them in the string by doubling up on double quotes but now VBA is saying I have an invalid character in that string (that being the first dollar sign). I am really confused on how to fix this. Any help would be greatly appreciated.
gRange = ""$A$1:$F$2""
Whenever I have issues in VBA with extra quotes in strings, I always fall back on using Chr(34) to replace.
gRange = Chr(34) & "$A$1:$F$2" & Chr(34)
Chr() MSDN Reference
I found a solution using an if Statement like so:
If sheetName = "Totals" Then
ChartData.ActiveSheet.ListObjects("Table1").Resize Range("$A$1:$F$2")
Else
ChartData.ActiveSheet.ListObjects("Table1").Resize Range("$A$1:$G$2")
End If
Instead of using a string.

Finding multiple instance of a variable length string in a string

I'm trying to extract my parameters from my SQL query to build my xml for an SSRS report. I want to be able to copy/paste my SQL into Excel, look through the code and find all instances of '#' and the appropriate parameter attached to it. These paramaters will ultimately be copied and pasted to another sheet for further use. So for example:
where DateField between #FromDate and #ToDate
and (BalanceFiled between #BalanceFrom and #BalanceTo
OR BalancdField = #BalanceFrom)
I know I can use Instr to find the starting position of the first '#' in a line but how then do I go about extracting the rest of the parameter name (which varies) and also, in the first two lines of the example, finding the second parameter and extracting it's variable lenght? I've also tried using the .Find method which I've been able to copy the whole line over but not just the parameters.
I might approach this problem like so:
Remove characters that are not surrounded by spaces, but do not
belong. In your example, the parentheses need to be removed.
Split the text using the space as a delimiter.
For each element in the split array, check the first character.
If it is "#", then the parameter is found, and it is the entire value in that part of the array.
My user-defined function looks something like this:
Public Function GetParameters(ByRef rsSQL As String) As String
Dim sWords() As String
Dim s As Variant
Dim sResult As String
'remove parentheses and split at space
sWords = Split(Replace(Replace(rsSQL, ")", ""), "(", ""), " ")
'find parameters
For Each s In sWords
If Left$(s, 1) = "#" Then
sResult = sResult & s & ", "
End If
Next s
'remove extra comma from list
If sResult <> "" Then
sResult = Left$(sResult, Len(sResult) - 2)
End If
GetParameters = sResult
End Function

Stack overflow when replacing ' with '' in VB 6.0

I'm looking into some legacy VB 6.0 code (an Access XP application) to solve a problem with a SQL statement by the Access app. I need to use replace single quotes with 2 single quotes for cases where a customer name has an apostrophe in the name (e.g. "Doctor's Surgery":
Replace(customerName, "'", "''")
Which will escape the single quote, so I get the valid SQL:
SELECT blah FROM blah WHERE customer = 'Doctor''s Surgery'
Unfortunately the Replace function causes an infinite loop and stack overflow, presumably because it replace function recursively converts each added quote with another 2 quotes. E.g. one quote is replaced by two, then that second quote is also replaced by two, and so on...
----------------EDIT---------------
I have noticed (thanks to posters) that the replace function used in this project is custom-written:
Public Function replace(ByVal StringToSearch As String, ByVal ToLookFor As String,
ByVal ToReplaceWith As String) As String
Dim found As Boolean
Dim position As Integer
Dim result As String
position = 0
position = InStr(StringToSearch, ToLookFor)
If position = 0 Then
found = False
replace = StringToSearch
Exit Function
Else
result = Left(StringToSearch, position - 1)
result = result & ToReplaceWith
result = result & Right(StringToSearch, Len(StringToSearch) - position - Len(ToLookFor) + 1)
result = replace(result, ToLookFor, ToReplaceWith)
End If
replace = result
End Function
Apparently, VB didn't always have a replace function of it's own. This implementation must be flawed. An going to follow folk's advice and remove it in favour of VB 6's implementation - if this doesn't work, I will write my own which works. Thanks everyone for your input!
Are you sure that it's not a proprietary implementation of the Replace function?
If so it can just be replaced by VB6's Replace.
I can't remember which version it appeared in (it wasn't in Vb3, but was in VB6) so if the original code base was vb3/4 it could be a hand coded version.
EDIT
I just saw your edit, I was Right!
Yes, you should be able to just remove that function, it'll then use the in build VB6 replace function.
We use an VB6 application that has the option of replacing ' with ` or removing them completely.
You could also walk through the letters, building a second string and inserting each ' as ''.
I just tried this in Access and it works fine (no stackoverflow):
Public Function ReplaceSingleQuote(tst As String) As String
ReplaceSingleQuote = Replace(tst, "'", "''")
End Function
Public Sub TestReplaceSingleQuote()
Debug.Print ReplaceSingleQuote("Doctor's Surgery")
End Sub

Resources