Can I make my VBA code automatically update the cell location?

h711

Board Regular
Joined
Jun 23, 2008
Messages
164
Hi, if I write VBA code to modify cell B3. Later on I inserted a new row above it, so now B3 became B4. The problem is my VBA code will still modify cell B3 every time I run it, not the new location B4.

Is there a way to make VBA code automatically update the cell location? Just like if you use = assignment in a cell, the referred cell will be automatically updated by excel every time you insert or delete rows/columns.


Thanks for your help.

Jianhua Huang
 

Some videos you may like

Excel Facts

Move date out one month or year
Use =EDATE(A2,1) for one month later. Use EDATE(A2,12) for one year later.

VoG

Legend
Joined
Jun 19, 2002
Messages
63,650
You could make the cell a named range (Insert > Name > Define) then refer to it as the range name e.g. Range("MyRange")
 

h711

Board Regular
Joined
Jun 23, 2008
Messages
164
Thanks for the replay. could you give me a simple example for how to do this?

For example, here is a simple macro I recorded to insert abc to cell B2:

Sub Macro1()

Range ("B2").Select
ActiveCell.FormulaR1C1 = "abc"
Range ("B3").Select

End Sub

Now how can I modify this code to auto update this "B2" to a new location if I insert/delete row/column that changes the cell location?

Thanks you very much for your help!!!!!
 

VoG

Legend
Joined
Jun 19, 2002
Messages
63,650
I named cell B2 as MyRange and ran this macro

Code:
Sub example()
Range("MyRange").Value = "abc"
End Sub

which placed abc in B2. I then deleted the contents of B2, inserted 3 rows above it then ran the macro again. abc was written into B5 (which now has the name MyRange).
 

Watch MrExcel Video

Forum statistics

Threads
1,122,564
Messages
5,596,875
Members
414,106
Latest member
Tigretto

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top