2

Im trying to create a VBAformula that will fill excel with a formula. i've got this VBA code

Dim ws As Worksheet
Dim u As Long
Set ws = ActiveSheet

u = 9

Dim used As Range
Set used = ws.UsedRange

Dim lastRow As Integer

lastRow = used.Row + used.Rows.Count - 2
ws.Range("K4:K" & lastRow).FormulaR1C1 = "=(R4C2-R4C" & u & ")/10"

but in excel I get this formula: =($B$4-$I$4)/10

is it possible with this code to get the formula looking like this? =(B4-I4)/10 without the $ symbol?

3
  • 2
    You are using R1C1 notation with absolute addressing. That corresponds to $ signs in the A1 notation. If you want relative addressing, don't use absolute addressing in R1C1 to being with. A relative address in R1C1 has the form of R[4]C[2], but you will have to correct the numbers because they are relative to where you put the formula. Commented Dec 19, 2019 at 14:51
  • 1
    Sidenotes, you might be specific about which worksheet to use instead of ActiveSheet. There are also better ways to search for a last used row. Commented Dec 19, 2019 at 14:59
  • @GSerg. Works. I Need to make it dynamic. I didn't know how buy thanks to you, I know now Commented Dec 19, 2019 at 15:18

1 Answer 1

4

I prefer .Formula over .FormulaR1C1 here:

 ws.Range("K4:K" & lastRow).Formula = "=(B4-I" & u & ")/10"

Also important: use Long instead of Integer to avoid a possible Overflow error:

 Dim lastRow As Long

EDIT:

I'm not sure exactly what the final version of the formula should be in each successive column, but perhaps you're looking for the following:

Dim i As Long
For i = 0 To 3
     ws.Range("K4:K" & lastRow).Offset(, i * 7).FormulaR1C1 = "=(R[]C2-R[]C[-" & u & "])/10"
Next

This keeps the B absolute and the rows and other column relative.

Sign up to request clarification or add additional context in comments.

7 Comments

That works, but the I column will also chance. After column I IT will go to column R and other columns after that
What is the column logic then? That is not in your original question.
Column logic is column +7 column and that 4 Times (in a loop i hot figured out)
Does B change as well or should that be absolute?
B should be static
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.