Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using another cell value to reference a range

Tags:

excel

vba

I have a work sheet that has some data in it. To simplify adding it into an email, I've created some code that upon a button press would select a range of cells and save it as an image to upload into email. The current code is the following:

Sub Button3_Click()
'
' Button3_Click Macro
'

'
Range("A1:D43").Select
ActiveWindow.SmallScroll Down:=-39
Selection.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
End Sub

I want to use a different cell to reference the range. So for example in cell J1 I would insert "A1", and in sell K1 I would insert "D43" to find my range so the range could be updated without having to edit the code. Is this possible? Thanks!

like image 485
Brandon Bezanson Avatar asked Oct 13 '18 15:10

Brandon Bezanson


People also ask

How do you reference a cell based on another cell value?

Click the cell where you want to enter a reference to another cell. Type an equals (=) sign in the cell. Click the cell in the same worksheet you want to make a reference to, and the cell name is automatically entered after the equal sign. Press Enter to create the cell reference.

How do you create a dynamic cell reference in Excel?

To create an Excel dynamic reference to any of the above named ranges, just enter its name in some cell, say G1, and refer to that cell from an Indirect formula =INDIRECT(G1) .

How do you auto populate a cell based on data from another cell?

Click and hold the left mouse button, and drag the plus sign over the cells you want to fill. And the series is filled in for you automatically using the AutoFill feature.


1 Answers

Welcome to Stackoverflow :)

A1 can be written as Range("J1").Value and D43 can be written as Range("K1").Value. So "A1:D43" can be written as Range("J1").Value & ":" & Range("K1").Value

Simply replace Range("A1:D43").Select with Range(Range("J1").Value & ":" & Range("K1").Value).Select

BTW, avoid using the .Select. You may want to see How to avoid using Select in Excel VBA

Your code can be written as

Range(Range("J1").Value & ":" & Range("K1").Value).CopyPicture _
Appearance:=xlScreen, Format:=xlBitmap

I am assuming that Range("J1") and Range("K1") are in the same sheet as from where you want to make the selection. If not then fully qualify the cells. For Example

Sheet1.Range(Sheet2.Range("J1").Value & ":" & Sheet2.Range("K1").Value)

Change Sheet1 and Sheet2 as applicable.

As jeeped showed in his post, you can also write the above as

Sheet1.Range(Sheet2.Range("J1").Value, Sheet2.Range("K1").Value).CopyPicture _
Appearance:=xlScreen, Format:=xlBitmap
like image 54
Siddharth Rout Avatar answered Oct 01 '22 23:10

Siddharth Rout