简体   繁体   中英

VBA Excel, formula referencing another cell with variable address

I need to insert a simple formula in one cell that references 2 cells below the cell where the formula is inserted into. As I will be inserting this formula in many different places, the "2 cells below" addresses are always changing.

So in cell AB200 for example, I want to insert a formula =sum(AB202 * TextBox3.Value) , TextBox3.Value being the value of a text box field entered previously in the macro.

The procedure will then be repeated but with a different address and different Text variable.

I am OK with the loop so I just need the VBA code to:

  1. write the formula based on a LastRow.Offset(16, 1). position.
  2. to code the address of 2 cells below the cell where the formula will be entered and
  3. completing the formula with the multiplication of the text variable.

The code to reference the cell 2 rows below the one containing the formula:

Activecell.FormulaR1C1="=R[2]C"

Read about R1C1 reference style if you are not familiar with that.

For Question 3), add something like this:

Activecell.FormulaR1C1="=R[2]C*" & YourTextVariable

Hopefully your text variable will actually have a number in it, otherwise you will be trying to multiply a number with a text, which obviously won't work.

As for your question number 1), I have no idea what you mean here. :) Maybe this?:

cells(Activecell.specialcells(xllastcell).Offset(16, 1).row,Activecell.column).FormulaR1C1="=R[2]C*" & YourTextVariable

If this is not what you mean, you can either google "last cell VBA", or if you are really lazy, clarify it here so that we can answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM