VBA R1C1 formula calculation with cell in another worksheet - excel

ws2.Cells(87, col - 2).FormulaR1C1 = "=R[-5]C[0]-'Another Sheet'!F89"
When I run the above code, the result would be, "=AW83- 'Another Sheet'!'F89", which returns an error because the ' between ! and F89. I tried to use " & " but it does not work this way. Does anyone know how to solve this? Thanks in advance!!

You cannot mix R1C1 and A1-notation in a formula. If you use FormulaR1C1, you have to provide all addressen in R1C1-notation. You can use Application.ConvertFormula to convert your F89:
dim r as range
set r = ws2.Cells(87, col - 2)
r.FormulaR1C1 = "=R[-5]C[0]-" & _
Application.ConvertFormula("'Another Sheet'!F89", xlA1, xlR1C1, , r)

Related

Combining IF formulas in Excel with variable ranges [duplicate]

I want to plug a range object into a formula. An example should look roughly like this:
Dim x As Range
Set x = Range(Cells(1, 1), Cells(2, 1))
Range("C1").Formula = "=SUM(" & x & ")"
The result should be "=SUM(A1:A2)" in cell C1.
The point is to plug the the range object into a formula. I used SUM as an example, the real formula is more complicated.
I guess there is an easy answer to this, e.g. some method for a range object, but I have't found it after some pondering ...
Thanks in advance,
Dainis
You need
Range("C1").Formula = "=SUM(" & x.Address(False, False) & ")"
See also
http://www.dailydoseofexcel.com/archives/2004/04/16/worksheet-formulas-in-vba-part-i/
http://www.dailydoseofexcel.com/archives/2004/04/16/worksheet-formula-in-vba-part-ii/
Use x.address, that should do the trick

get the differences between 2 Integer columns into third column

I have to calculate the difference between the values of 2 columns(firstCol and lastCol) and set those differences in a different column(NextColumn). The row count keeps changing, so I have to calculate the rowCount before calculating the difference. I'm trying to write a loop using Range so that the difference can be calculated but it doesn't seem to work.
For i = 3 To lastRow
Range(Cells(3, NextColumn), Cells(lastRow, NextColumn)).FormulaR1C1 = "=Range(Cells(i, firstCol),Cells(i,firstCol)).Value - Range(Cells(i, lastCol),Cells(i,lastCol)).Value"
Next i
Any help would be greatly appreciated!
Thank you
Nick
For any input of "i" into the formula, you need to use " & i & " when using using a formula="", such as:
"=A" & i & "+B" & i
When you change to just a formula that doesn't input a formula to the cell (math happens in VBA), you can ignore the Excel formatting and "" blocking, such as:
= Cells(i,"A").Value + Cells(i,"B").Value
Make sure to use your loop variable where appropriate, so that you would have an outcome in a loop like:
Dim i as Long
For i = 1 to 10
Cells(i,"C").Formula = Cells(i,"A").Value + Cells(i,"B").Value
Next i
Why looping ? Unless I misunderstood the question, something like this should do the trick:
Range("X3:X"& lastrow).Formula = "=C3-D3"
The formula will adjust.
vba needs to be outside the quotes and you do not need the loop:
Range(Cells(3, NextColumn), Cells(lastRow, NextColumn)).Formula = "=" & Cells(3, firstCol).Address(0, 0) & "-" & Cells(3, lastCol).Address(0, 0)
No loop needed. Excel will change the relative references as needed.

Excel VBA: inserting WHEN formula into specific range of cells with variable changing column

Hello dear StackOverflow users,
My issue is regarding inserting a Formular via Macro into specific range of cells. Again, again and again.
So the Basic function of the formula should be the following:
=WHEN('ZEK '!F3="X";"6";WHEN('ZEK '!G3="X";"8";"1"))
In my macro it has to Change the column for the next specific range.
This is Happening in a for Loop for i growing.
meaning --> =When('ZEK '!$F$"& i+2 &".......
or in any other Syntax that should work. My try fairly does not, thats why I need your help.
This is my Initial try where i exchanged literally everything with strings:
Sub 123()
Dim a,b,c As String
a = 1
b = 6
c = 8
....
'used and declared variables k, x, f, a, b, c
Range(Cells(k + 2, 5), Cells(k + 27, 5)).FormulaR1C1 = _
"=WHEN('ZEK'!$F$" & f & "=" & x & ";" & a & ";WHEN('ZEK'!$G$" & f & "=" & x & ";" & b & ";" & c & "))"
End Sub
With that i get Runtime Error 1004. (changed it to .Formula from .FormulaR1C1)
I hope i gave enough Information, so that you could help me.
This really does not have to be performant, i just Need to get the formula into about 100.000 cells with i changing for each Range of cells
I think it's a language problem... Try
"=IF('ZEK'!$F$" & f & "=" & x & "," & a & ",IF('ZEK'!$G$" & f & "=" & x & "," & b & "," & c & "))"
Notice the use of IF and , as a delimiter instead of ;. Is WHEN even a valid worksheet function? To be honest I don't know if the worksheet functions get translated or not when setting the formula via VBA. The delimiters are adapted though.
edit: there is also the .FormulaLocal property that should work with ; as delimiter! So change .Formula to .FormulaLocal. This will probably cause an error if you execute it on a machine that uses , as default delimiter so I'd try to stick with .Formula.

Dynamic formula autofill

I would like to know how may i convert this code into dynamic range autofill for the column I to enable the freedom of editing the excel sheet at a later time without the need to adjust the vba code.
Sub Rowcount()
'Charles, M
Dim H As Long
Set sh = Worksheets("Report-Charles, M")
H = sh.UsedRange.Rows.Count
Range("I2:I" & H).Formula = "=IF((AND(OR(E2=""Unrated"",E2=""""),OR(G2<>""Unrated"",G2<>""""))),G2,IF(E2>=""4,25"",""High Performance"",IF(E2<""3,35"",""Low Performance"",IF(AND(E2>=""3,35"",E2<""4,25""),""Medium Performance"",""Unrated""))))"
MsgBox (H) & "Rows have been Autofilled with 3 scale Rating Results"
End Sub
Have a look into the AutoFill function:
Range("I2:I" & H).AutoFill Destination:=Range("I2:I2000"), Type:=xlFillDefault
First off, you are only implicitly referencing the Report-Charles, M as the ActiveSheet property to put the .Formula into; not explicitly with direct reference.
Second, To assign the formula, use a direct .Formula write, the Range.AutoFill method or the Range.FillDown method.
Lastly, writing a formula .Formula through VBA should be done with EN-US syntax and regional settings. If you want to use non-EN-US regional settings like 3,35 or 4,25 then use the Range.FormulaLocal property.
Above all else, treat numbers as numbers; not as text-that-look-like-numbers.
with Worksheets("Report-Charles, M")
h = .UsedRange.Rows.Count
.Range("I2:I" & H).FormulaLocal = _
"=IF((AND(OR(E2=""Unrated"", E2=TEXT(,)), OR(G2<>""Unrated"", G2<>TEXT(,)))), G2, IF(E2>=4,25, ""High Performance"", IF(E2<3,35, ""Low Performance"", ""Medium Performance"")))"
.Range("I2:I" & H).Formula = _
"=IF((AND(OR(E2=""Unrated"", E2=TEXT(,)), OR(G2<>""Unrated"", G2<>TEXT(,)))), G2, IF(E2>=4.25, ""High Performance"", IF(E2<3.35, ""Low Performance"", ""Medium Performance"")))"
end with
with Worksheets("Report-Charles, M")
'any of the following will fill column I with formulas to the last row in .UsedRange
'all of the following assumes a valid formula in I2
h = .UsedRange.Rows.Count
.Range("I2:I" & H).Formula = .Range("I2").Formula
.Range("I2:I" & H).FillDown
.Range("I2:I" & H).DataSeries Rowcol:=xlColumns, Type:=xlAutoFill
.Range("I2").AutoFill Destination:=.Range("I2:I" & H), Type:=xlFillDefault
end with
I've shortened one IF condition since the AND was unnecessary and Medium was the default response. Using TEXT(,) is the same as saying "" and does not have to double-up double-quotes.

Inserting formulas w/ FOR NEXT Loop

Couldn't find a thread that would answer my question, os here I am. Please provide a link if there is one that I have not found.
Using Excel 2010
The comments should be sufficient to show what I'm trying to do.
I'm getting the Application-defined or Object-defined error (Runtime error 1004) I just can figure it out. Any help would be appreciated. Side note: I can get the loop to work when a formula like =if(A1=B1,"",3) If actually places the formula in the cell and show 3 in each cell when the condition is met. it just adding the Column,Row, I've tried & Range($, C) &, all sorts of combinations so, show me how much of a boob I am and help me with the SIMPLE fix that eludes me.
Thanks in advance.
Private Sub CommandButton1_Click()
Dim R, C As Integer
Dim Frmla1, Frmla2, Frmla3 As String
R = 4 'Initial Row #
C = 2 'Initial Column #
Frmla1 = "=IF('Log Sheet'!" '1st half of the formula
Frmla2 = "="""","""",'Log Sheet'!" '2nd half of the formula
Frmla3 = ")" 'Closing Parenthesis
' The Cells should have incremental Column,Row Identifiers.
' The following is what I want in each cell.
' The problem is trying to get the B4 and B5 into the formula.
' Formula "=IF('Log Sheet'!B4="","",'Log Sheet'!B4)
' Formula "=IF('Log Sheet'!B5="","",'Log Sheet'!B5)
For R = 4 To 301
ActiveSheet.Cells(R, C).Value = Frmla1 & R & C & Frmla2 & R & C & Frmla3
R = R + 2
Next R
End Sub
It looks like you should be using the R and C to reference a Range.Cells property that you can return a Range.Address property from.
For R = 4 To 301 Step 2
ActiveSheet.Cells(R, C).Formula = _
Frmla1 & Cells(R, C).Address(0, 0) & Frmla2 & Cells(R, C).Address(0, 0) & Frmla3
Next R
I've also removed your R = R + 2 and changed the Step of the For ... Next to increment by 2. You shouldn't self-increment a For ... Next inside the loop.
I changed the Range.Value property assignment to Range.Formula property. While your method often works, it wasn't correct and if the cells were formatted as Text, the formulas would come into the cells as text-that-looks=like-a-formula.
Your variable declarations should be more like the following.
Dim R As Long, C As Long
Dim Frmla1 As String, Frmla2 As String, Frmla3 As String
Each declaration should carry a variable type. Without it, they are declared as object/variant types,

Resources