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.
Related
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
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!
I am trying to write this formula into a cell via my script:
strFormulas(1) = "=IF(AND(I2<12.2,I2>=8.2),"t","f")"
And it keeps coming up as an error, even though it works just fine in the actual sheet if I manually input it into the cell. What is it expecting me to do here?
You need to escape quotes. Try this:
strFormulas(1) = "=IF(AND(I2<12.2,I2>=8.2),""t"",""f"")"
The issue that you are running into is that " is interpreted as beginning or ending a VBA string. So VBA parses your expression as
strFormulas(1) = "=IF(AND(I2<12.2,I2>=8.2),"
with "garbage" at the end. This "garbage" is what it is complaining about. If you need to include a " within a VBA string, use "".
So I am using Instr with Evaluation and facing some difficulties
The code is as follows
myIneq=">"
myString1="Hello"
myString2="el"
Evaluate( "Instr(" & myString1 & "," & myString2 & ")" & myIneq & cstr(0)
I am getting an Error 2029. Based off this msdn link I am assuming it is trying to evaluate "Hello" as a variable name. What is the work around for this, I know there must be one.
Thanks
I infer from the Error 2029 (#NAME?) and the link that you're using Excel. In this case the answer is simple. Application.Evaluate evaluates Excel expressions, not VBA code. That is, any functions you call in your expression have to be things you could call from an Excel formula. (And you're correct that Excel is trying to evaluate the value of a symbol it doesn't recognize, and is thus giving you back a #NAME? error.)
There is an Excel worksheet function, FIND, that does pretty much the same thing that the VBA function Instr does, so if your example is not too simplified, that might be all you need to do.
I just typed this into the Immediate window:
x="Hello"
y="el"
?Evaluate("FIND(""" & y & """, """ & x & """)")
2
ineq = ">"
?Evaluate("FIND(""" & y & """, """ & x & """)" & ineq & "0")
True
and it seems to work.
Note that Evaluate is a function, so it expects to receive a string argument, and then return what that string evaluates to if treated as an Excel formula-syntax expression. In your example, you don't seem to be doing anything with the return value, so I thought I'd mention it.
"Evaluate" doesn't understand all excel functions.
For example, trying to evaluate "instr" will give an Error 2029. But there is a nice workaround:
"evaluate" recognizes all added vba functions of your excel sheet
so just wrap a single-line function around the reluctant function.
Code will be similar to this:
Sub test()
MsgBox Evaluate(" Instring(""Hello"",""el"") ")
Msgbox "\o/ ! ... I owe a beer to someone out there"
End Sub
Function Instring(a, b)
'make instr visible to 'evaluate'
Instring = InStr(a, b)
End Function
You're evaluating the string InStr(Hello,el).
Obviously, that's not what you want.
You need to use a quoted string literal.
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