I am wrestling with the syntax of this one line of some code. the formula with "IfError" seems to have the wrong syntax. I believe I have the quotes in the right places.
Dim j As Integer
Dim MidPointE As String
Dim Dist As String
Dim Allocation As String
MidPointE = "AM"
Dist = "AN"
Allocation = "AO"
for J= 1 to 300
Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE & CustomerLast & ", "")"
Cells(j, Allocation).Formula = "=" & Allocation & j & "* S" & CustomerLast
Next J
You can also assign multiple formulas at the same time:
Range("AN1:AN300").Formula = "=IFERROR(AM1 / AM$" & CustomerLast & ", """")"
Range("AO1:AO300").Formula = "=AO1 * S$" & CustomerLast
I also recommend looking into Excel Tables and Structured References
To avoid the circular reference issue, you can calculate the formulas and assign the values directly:
Range("AN1:AN300") = Evaluate("IFERROR(AM1:AM300 / AM$" & CustomerLast & ", """")")
Range("AO1:AO300") = Evaluate("INDEX(AO1:AO300 * S$" & CustomerLast & ",)")
Try this:
Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE & CustomerLast & ", """")"
Quotes inside a string literal must be escaped - and that's done by doubling them up.
It's at the end here
& ", "")"
The two quotes between the comma and ) end the string and start a new one.
'first string
","
'second string
")"
Since you can't just throw two strings together like that, i would replace the two quotes with the CHR equivalent. Should look something like this:
Cells(j, Dist).Formula = "=IFERROR(" & MidPointE & j & " / " & MidPointE & CustomerLast & ", "& CHR(034) & CHR(034) & ")"
'pretty sure 034 is the ascii code for "
Related
I'm looping through columns and storing them in values s and s1. I need to add count order for as many lines as it's needed for which I'm trying to use j index. Getting picture like this all the time:
And the desired result should be as follows:
s = ""
s1 = ""
j = 1
Do
s = j & ". " & s & Workbooks(Filename).Sheets(1).Cells(i, 2).Offset(1, 0).Value & vbCrLf
s1 = j & ". " & s1 & Workbooks(Filename).Sheets(1).Cells(i, 3).Offset(1, 0).Value & vbCrLf
i = i + 1
j = j + 1
Loop While Workbooks(Filename).Sheets(1).Cells(i, 3).Value <> ""
The code should be incremented like this:
s = s & j & ". " & Cells(i, 2).Offset(1, 0) & vbCrLf
Thus, the s value is incrementing over itself.
In general, whenever such problems appear and it is tough to understand why a string is being formatted, try to debug step-by-step. E.g., write Stop on the code and print the string, which is avialable up to now. Like this:
Do
s = s & j & ". " & Cells(i, 2).Offset(1, 0) & vbCrLf
s1 = j & ". " & s1 & Cells(i, 3).Offset(1, 0) & vbCrLf
i = i + 1
j = j + 1
Debug.Print s
Stop
Loop While Cells(i, 3) <> ""
Then the magic becomes easier to understand. Pressing F8 and checking the current values with hovering over them in VBE is another option for step-by-step debugging.
Debugging VBA, Locating Problems, and Troubleshooting Methods
I have a piece of code that loops down a column and inserts a formula into each cell in that column. The code runs, the only problems is that each cell the formula is inserted into displays #Value! Does anyone know how to fix this?
Here is the piece of code with the problem:
Dim j As Long
'Loop down the rows in mainfile
For j = 2 To lastFullRow2
' Make each argument a string, then concatenate it all all into large string
Dim firstArgument As String
firstArgument = "ws_multidax.Range(" & valuecolumnLetter & "2:" & valuecolumnLetter & lastFullRow1 & ")"
Dim secondArgument As String
secondArgument = "ws_multidax.Range(" & parameter1columnLetter & "2:" & parameter1columnLetter & lastFullRow1 & ")"
Dim thirdArgument As String
thirdArgument = "ws_multidax.Range(" & parameter2columnLetter & "2:" & parameter2columnLetter & lastFullRow1 & ")"
Dim fourthArgument As String
fourthArgument = "ws_multidax.Range(" & parameter2columnLetter & "2:" & parameter2columnLetter & lastFullRow1 & ")"
Dim condition3 As String
condition3 = "ws_mainfile.Range(" & "D2:" & D & j & ")"
Dim patid1 As String
patid1 = "ws_multidax.Range(" & "D2:" & D & lastFullRow2 & ")"
With ws_mainfile
Dim commandstring As String
'The formula we want is a concatenated string
commandstring = "{=INDEX(" & firstArgument & ",MATCH(1,(" & secondArgument & "=" & condition1 & ")*(" & thirdArgument & "=" & condition2 & ")*(" & patid1 & "=" & condition3 & "),0))}"
'Insert the formula into each cell as the loop goes down the rows
ws_mainfile.Range("AN" & j).Formula = Eval(commandstring)
'ws_mainfile.Range("AN" & j).Formula = commandstring
End With
Next j
The #Value! gets put into the cells when I run the line with the Eval(commandstring). When I run the line with just formula = commandstring, the formula gets put in each cell, but it does not solve.
Your code has 2 problems:
You are putting in the curly braces of an array formula manually, don't do this
You are putting in an array formula as a regular formula
So to correct, do the following:
'1. Change this line:
commandstring = "{=INDEX(....)}"
'And simply remove the curly braces {} from its beginning and end
commandstring = "=INDEX(....)"
'2. Change this line:
ws_mainfile.Range("AN" & j).Formula = Eval(commandstring)
'To use the .FormulaArray property instead of just .Formula:
ws_mainfile.Range("AN" & j).FormulaArray = commandstring
You're on the right track. There's no need to use the eval function, as you have built a string formula in code. The problem is you have surrounded it with the braces, which excel treats as if you had entered text.
Try this instead:
commandstring = "=INDEX(" & firstArgument & ",MATCH(1,(" & secondArgument & "=" & condition1 & ")*(" & thirdArgument & "=" & condition2 & ")*(" & patid1 & "=" & condition3 & "),0))"
'Insert the formula into each cell as the loop goes down the rows
ws_mainfile.Range("AN" & j).Formula = commandstring
I'm trying to write vba code so that every time I type a number, it becomes a stock ticker after "HK Equity" is added by vba code. Then spreadsheet can return its RSI using Bloomberg function BTP. For example, when I type "1" in a cell, spreadsheet will return the RSI of stock "1 HK Equity" using Bloomberg function =BTP($D3,E$2,"RSI","TAPeriod=14","DSClose=LAST_PRICE","Per=d").
Here are my code:
Sub RSI()
Dim num As Integer
num = Sheets("sheet2").Cells(3, 2).Value
Dim numString As String
numString = CStr(num)
Dim ticker As String
ticker = numString + "HK Equity"
Dim rsiString As String
rsiString = Sheets("sheet2").Cells(4, 2).Value
Sheets("sheet2").Cells(5, 2).Value = "=BTP(" & ticker & "," & rsiString & "," & "RSI" & ", " & "TAPeriod=14" & "," & "DSClose=LAST_PRICE" & "," & "Per=d" & ")"
End Sub
When I run the code it says Run-time Error '1004': application-defined or object-defined error. And debugger says the last command has a problem (i.e. Sheets("sheet2").Cells(5, 2).Value = "=BTP....) What's wrong with this command? THX!!
May you check the output of BTP formula?
' =BTP(1 HK Equity,rsi string,RSI, TAPeriod=14,DSClose=LAST_PRICE,Per=d)
Sheets("sheet2").Cells(5, 2).Value = "=BTP(" & ticker & "," & rsiString & "," & "RSI" & ", " & "TAPeriod=14" & "," & "DSClose=LAST_PRICE" & "," & "Per=d" & ")"
seems you have miss all escape character
"=BTP(""" & ticker & """,""" & rsiString & """,""RSI"",""TAPeriod=14"",""DSClose=LAST_PRICE"",""Per=d"")"
I need to write in the cells from Cells(1,1) to Cells(501,1) the formula
=FDSC("-",$C$3,"FG_PRICE(D1)") for line 1
=FDSC("-",$C$3,"FG_PRICE(D2)") for line 2
=FDSC("-",$C$3,"FG_PRICE(D3)") for line 3
Now my vba code is the following one :
Range(Cells(1, 1), Cells(1 + 500, 1)).FormulaR1C1 = "=FDSC(""" & "-" & """,R1C3,""" & " FG_PRICE(RC[3]) " & """)"
I've tested everypart of the code to determine that the last part (FG_PRICE...) is the one that is not working!
The formule that is written in Excel is :
=FDSC("-",$C$1,"FG_PRICE(RC[3])")
How can i do to have D1,D2,etc... and not RC[3]??? I've tried a few things but i can't find it!
Thank you very much for your time and your help!
Use chr(34) to represent quotation marks when you are already working inside quotation marks. For example, change your forumula above to the following:
Range(Cells(1, 1), Cells(1 + 500, 1)).FormulaR1C1 = "=FDSC(" & chr(34) & "-" & chr(34) & ",$C$1," & chr(34) & "FG_PRICE(D1)" & chr(34) & ")"
To put it in a loop, just do the following:
Sub writeFormulas()
Dim i as Integer
For i = 0 to 2
Range(Cells(1, 1), Cells(1 + 500, 1)).FormulaR1C1 = "=FDSC(" & chr(34) & "-" & chr(34) & ",$C$1," & chr(34) & "FG_PRICE(D" & i+1 & ")" & chr(34) & ")"
next i
End Sub
This was my previous post Insert COUNTIF formula when you have variable holding the value.
Below was the Solution.
Range("Q" & minRow + 1).Formula = "=COUNTIF(P$" & minRow & ":P" & minRow & ",P" & minRow + 1 & ")=0"
I have a new Question. What if the column is a variable?
What is the syntax if both are Variables (column and row are unknown and their values stored in a variable) and what is the syntax if column is variable and row is a number?
I have tried these ways
"=COUNTIF( & Columnz $1: & Columnz &2 ,& Columnz &2000)=0"
and these way
"=COUNTIF( "& Columnz" $1: " & Columnz"2,& Columnz &2000)=0"
To define a range, you can also use Cells, for instance:
ActiveSheet.Cells(1,1) '=Range ("A1")
ActiveSheet.Cells(1,"A") '=Range ("A1")
If you want to define a range, you can do:
Range(Cells(1,1), Cells(10,5)) '=Range("A1:E10")
Thus, you can do:
'where Columnz is a Long or an Integer
"=COUNTIF(" & Range(Cells(1, Columnz), Cells(2, Columnz)).Address & "," & Cells(2000,Columnz).Address & ")=0"
I'd like to add to the nice above responses, that OFFSET is very usefull, specially while looping.
e.g.:
With Range("B3")
For i = 1 to 10
.offset(0, i) = "something"
Next i
End With
You can also make your VBA much more readable, and eliminate the need for "variable formulae" by using the native Excel (R1C1) syntax. Like
myRange.offset(0,i).FormulaR1C1 = "=SUM(R1C[-1]:RC[-1])"
which means sum from row 1 of previous column till same row of previous column.
Finally, you can use the "dual arguments" version of RANGE(cell1, cell2):
With Range("B3")
For i = 1 to 10
.offset(0, i).formula = "=SUM(" & Range(cells(10, 1),cells(10, i)).address & ")"
Next i
End With
The row number is already a variable in your example: minRow. String concatenation is done with an ampersand (&) in VB/A. You are halfway right but missing the second ampersand. You can think about it like this:
"first string" & variable1
This is a concat between 2 strings, if you want to add a third string, you have to use another ampersand:
"first string " & variable1 & "second string"
Your code:
"=COUNTIF(" & columnz & "$" & minRow & ":" & columnz & minRow & ",P" & (minRow + 1) & ")=0"
In response to your comments:
"=COUNTIF(" & columnz & "$1" & ":" & columnz & "1,P2)=0"
Just remove the variable from the string and include the row in the other string literals.
it can be somthing like that:
startRow = 3
endRow = 17
myRange=("B" & StartRow & ":" & "B" & EndRow)
then your range = ("B3":"B17")