Macro Relative References
- 03:26
Understand which cells Excel will select when playing a Macro
Downloads
No associated resources to download.
Glossary
Absolute References VBATranscript
When we're recording macros in Excel, it's important to know how Excel tracks the cursor and what happens when we go and select cells when we're recording.
Normally when we record a macro and we go and record ourselves clicking into a particular cell, every time we play that macro back again, it will go absolutely to that exact same cell and do that job. So if I record myself clicking onto cell B5, entering in my name and then pressing enter, then every time I run that macro, that's exactly what it will do. It'll go to B5, enter in my name and then press enter. So those are the actions I've recorded. Sometimes though, we don't want to do that. What we want to do is we want to use something called relative references. So we want to actually record the relative movement of our cursor as part of our recording. Let's do an example. So I've got my cursor in A8 and we're gonna do a simple recorded macro where we're gonna enter my name in. So before we start recording, we're gonna go and look at the Developer ribbon and see where this relative references option is. And you'll see it's just underneath the Record Macro button. So at the minute, it's off because there's no action on the button. If I go and click it and move my mouse away, you'll see that it stays highlighted with this dark gray background. If I click it again, I've now turned it off. So it's a toggle button, which you can turn on and off. So I've turned on relative references and now I'm going to record a macro. We're gonna give it a name.
EnterMyName2.
And again, for training purposes, we're gonna store this in this workbook. Click OK. So my cursor is currently in A8. I'm gonna go and select B8. And you could do that with the arrow cursor keys, or with your mouse. It doesn't matter. I'm gonna enter my name and I'm gonna press enter. And now I'm gonna stop recording. I'm gonna use the shortcut Alt + L + R. Okay, so let's delete that and go and run our macro. Let's keep the cursor in cell B8, run our macro and see what happens. So the shortcut, you'll remember to open the run macro dialog box is Alt + F8.
We've now got two macros available to us. EnterMyName and EnterMyName2. I'm gonna go and select EnterMyName2 and we're gonna run that one.
You'll notice that my name has been entered into C8 because Excel recorded the relative movement of my cursor. When I started recording, my cursor was in A8. I moved to B8, which is one to the right. I entered my name and then stopped recording. When I run this macro now, it does exactly the same thing. It just goes one cell to the right, enters my name and then stops recording. So we've recorded a relative reference macro.