Excel VBA Formula Inside a String - vba

Trying to put a formula inside a string and can't get it working. Can someone help me turn this into a string? I know I need to do ""&"" in places, I just don't know where....
Dim form As String
form = =IFERROR(GETPIVOTDATA("[Measures].[Sum of Amount]",Pivot!$A$3,"[qAllData].[Year]","[qAllData].[Year].&[2.016E3]","[qAllData].[Month Name]","[qAllData].[Month Name].&["&$B9&"]","[qAllData].[PRODUCT_CODE]","[qAllData].[PRODUCT_CODE].&["&C$3&"]","[qAllData].[Product Name]","[qAllData].[Product Name].&["&C$4&"]")-C8-C7-C6-C5,0)

If your formual is verbatim what you have in the spreadsheet but you want to insert it with VBA then just:
Dim form As String
form = "=IFERROR(GETPIVOTDATA(""[Measures].[Sum of Amount]"",Pivot!$A$3,""[qAllData].[Year]"",""[qAllData].[Year].&[2.016E3]"",""[qAllData].[Month Name]"",""[qAllData].[Month Name].&[""&$B9&""]"",""[qAllData].[PRODUCT_CODE]"",""[qAllData].[PRODUCT_CODE].&[""&C$3&""]"",""[qAllData].[Product Name]"",""[qAllData].[Product Name].&[""&C$4&""]"")-C8-C7-C6-C5,0)"
This simply replaced each " by "" and wrapped the whole thing in quotes. VBA accepts it as a valid formula, though I am not sure that this is what you really want.

If it is a working formula and you just want it in a variable as a String, all you need to do is start and end it with double quotes (") and then double all inner quotes (""), like so:
form = "=IFERROR(GETPIVOTDATA(""[Measures].[Sum of Amount]"",Pivot!$A$3,""[qAllData].[Year]"",""[qAllData].[Year].&[2.016E3]"",""[qAllData].[Month Name]"",""[qAllData].[Month Name].&[""&$B9&""]"",""[qAllData].[PRODUCT_CODE]"",""[qAllData].[PRODUCT_CODE].&[""&C$3&""]"",""[qAllData].[Product Name]"",""[qAllData].[Product Name].&[""&C$4&""]"")-C8-C7-C6-C5,0)"

Related

How to count the number of empty spaces in front of a String in VBA?

I have a YAML file which I am reading using VBA Excel plugin. I am getting a String of each line. I need to count the number of empty spaces in the front of the first line so that it will be a marker to find the next key. Let me know how to do that.
Option Explicit
Function empty_spaces(str_input)
empty_spaces = Len(str_input) - Len(LTrim(str_input))
End Function
harun24hr, your answer does not work with " My String " and similar.

Formula works in excel but not in vba

the below formula works in a cell, but when I try to use it in VBA it gives syntax error. Why is it and what is the solution?. Thanks.
ThisWorkbook.Sheets("Sheet2").Cells(Lastrow + 1, 9).Formula = "=(SUMIFS(Sheet1!$B:$B,Sheet1!$O:$O,">0")/SUM(Sheet1!$B1:$B1000))*100"
The problem is with ">0" to use quotations inside a String you need to do the following:
"">0"" with double quotations VBA understands its a String inside the String.
instead of the end " of the String >0 some code and " the start of a new String.
You need to use single quotes for the string otherwise the string ends and will throw an error but there may be something else going on. What is your exact error?

excel vba formula construction double quotes versus single

I found answer under the title "Using variables in R1C1 formula construction" that makes my formula work. Can someone explain, the logic as to how a formula is constructed and stored in a cell.
Original:
=IF(ISNUMBER(SEARCH("IAV",RC[-2])),MID(RC[-2],FIND("IAV",RC[-2])+6,11),"")
Working:
sFRM = "=IF(ISNUMBER(SEARCH('IAV',RC[-2])),MID(RC[-2],FIND('IAV',RC[-2])+6,11),'')"
.Range("o2:o" & lr).FormulaR1C1 = Replace(sFRM, Chr(39), Chr(34))
thanks, inadvance
I think you are trying to figure out why there are single quotes in the VBA version, but double quotes in the excel sheet.
In VBA, to create a variable of type string, you put it inside quotation marks.
So the line:
myvar = "help"
causes the variable myvar to be a string with the value of help [without quotes]
But what if you wish to have quotation marks in your string? So you want myvar to actually be equal to
John said "Help"
If you tried to set a variable equal to this, VBA would treat the quotation mark as a symbol exiting the string and would cause an error, such as occurs in the following line:
myvar = "John said "Help""
This would not work, because VBA would see the second quotation mark and think that the string is complete (and equal to [John said ]) but then it doesn't know what the next character, 'H' is telling it to do.
There are a few ways to correct this, but your code does so by using single quotes and then replacing them with double quotes. The same line using that method is:
myvar = "John said 'Help'"
myvar = replace(myvar,chr(39), chr(34))
Here, the string originally has the desired sentence, but with single quotation marks around the word Help.
Chr(39) represents a single quotation mark and Chr(34) represents a double quotes. So the replace function changes all of the single quotation marks with double quotes.
Instead, you could have done this:
myvar = "John said " & chr(34) & "Help" & chr(34)
and it would have created the same string.
Your code sets the variable sFRM to the desired value with single quotes instead of double quotes and then replaces the single quotes with double quotes. The double quotes at the begining and end of the line of code are being used to denote that the letters inside them are to be put into a string.
The single quotation marks are being used as placeholders to be replaced. There are other ways to do this, but the method you have provided will work.

Isolate a a substring within quotes from an entire line

To start here is an example of a line I am trying to manipulate:
trait slot QName(PrivateNamespace("*", "com.company.assembleegameclient.ui:StatusBar"), "_-0IA") type QName(PackageNamespace(""), "Boolean") value False() end
I wrote a code that will go through and read through each line and stop at the appropriate line. What I am trying to achieve now is to read through the characters and save just the
_-0IA
to a new string. I tried using Trim(), Replace(), and indexof so far but I am having a ton of difficulties because of the quotation marks. Has anyone deal with this issue before?
Assuming your source string will always follow a strict format with only some data changes, something like this might work:
'Split the string by "," and extract the 3rd element. Trim the space and _
quotation mark from the front and extract the first 5 characters.
Dim targetstr As String = sourcestr.Split(","c)(2).TrimStart(" """.ToCharArray).Substring(0, 5)
If the length of the target string is variable it can be done like this:
Dim temp As String = teststr.Split(","c)(2).TrimStart(" """.ToCharArray)
'Use the index of the next quotation mark instead of a fixed length
Dim targetstr As String = temp.Substring(0, temp.IndexOf(""""c))

Using left double quotation marks in strings in VB

In following code, the usage of the string "“" (i.e. a left double quotation mark inside a string) results in a compile error in VB.NET:
StringVar = Replace(StringVar, "“", "“")
What’s going on here?
It seems as if you want to replace curly quotes with their HTML code equivalent.
On the first glance, your code is absolutely correct. The problem is that VB allows curly quotes in place of regular quotes in code (because Unicode is great, right?). That is, the following codes are all equivalent:
Dim str = "hello"
Dim str = “hello”
Dim str = "hello“
Now, if you want to use a quotation mark inside a string, VB doesn’t know whether the quotation mark is supposed to end the string or not. In C#, this would be fixed by escaping the quotation mark, i.e. in place of """ you’d write "\"". In VB, the same is done by doubling the quotation mark, i.e. """".
Back to your curly quote. The same as for straight quotes applies according to the VB language specification (¶1.6.4). So to write a curly quote in code, try the following:
StringVar = Replace(StringVar, "““", "“")
Unfortunately, I cannot try this code now and it’s altogether possible that the IDE simply replaces this by straight quotes. If that’s the case, an alternative is to use Chr or ChrW with the character code of the “left double quotation mark”:
StringVar = Replace(StringVar, ChrW(&H201C), "“")
Or, for symmetry, written in decimal (but I prefer hexadecimal for character codes):
StringVar = Replace(StringVar, ChrW(8220), "“")
Something else: the Replace function will probably soon be deprecated and doesn’t work everywhere (e.g. Windows Phone 7). Instead, use the Replace method of the String class:
StringVar = StringVar.Replace(, ChrW(8220), "“")
See http://msdn.microsoft.com/en-us/library/613dxh46%28v=vs.71%29.aspx
Try this:
StringVar = Replace(StringVar, "“", ChrW(&H8220))
It looks like you're searching for the ChrW function in the Microsoft.VisualBasic namespace, which is used to convert a Unicode character code into the actual character.
If you're trying to replace straight quotes in a string with curly quotes, try the following code:
'Declare a string that uses straight quotes
Dim origString As String = "This string uses ""quotes"" around a word."
'Create a new string by replacing the straight quotes from the original string
'with left-facing curly quotes
Dim newString As String = origString.Replace("""", ChrW(8220))
'Display the result
MessageBox.Show(newString)
Or, if you're trying to encode the left-facing curly quotes in a string by replacing them with an alternate notation (assuming the one you used in the question is correct), try the following code:
'Declare a string that uses left-facing curly quotes
Dim origString As String = "This string uses fancy " & ChrW(8220) & _
"quotes" & ChrW(8220) & " around a word."
'Create a new string by replacing the curly quotes with an arbitrary string
Dim newString As String = origString.Replace(ChrW(8220), "“")
'Display the result
MessageBox.Show(newString)