Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a Sheet and cell as variable

Tags:

excel

vba

I am new in VBA coding. Lets say I am retrieving value from Sheet3.Cell(23, 4) for a value, is there any way in the VBA code which let me set this as a variable?

For example, I have changed the interface and let the value stay at Sheet4.Cell(20,1), everywhere in my code which refer to Sheet3.Cell(23, 4) need to be changed to Sheet4.Cell(20, 1). I am thinking is there any best practice for coding VBA for situation like this?

like image 399
Steveng Avatar asked Mar 28 '12 11:03

Steveng


People also ask

Can a cell be a variable in VBA?

To use a range or a single cell as a variable, first, you need to declare that variable with the range data type. Once you do that you need to specify a range of a cell to that variable using the range object.

How do you assign a worksheet to a variable in VBA?

When we declare a variable, we need to assign a data type. We can also assign objects as data types. To assign a value to declared object variables, we need to use the word “SET.” The word “Set” refers to a new object in VBA. For example, the particular range of the particular worksheet.

How do you assign a variable to a cell in Excel?

Type “d” in the Name control of the New Name dialog, then click in the “Refers to” control. Click the cell directly to the right of the cell containing the “d” to specify the cell that the new variable represents.


1 Answers

Yes. For that ensure that you declare the worksheet

For example

Previous Code

Sub Sample()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet3")

    Debug.Print ws.Cells(23, 4).Value
End Sub

New Code

Sub Sample()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet4")

    Debug.Print ws.Cells(23, 4).Value
End Sub
like image 106
Siddharth Rout Avatar answered Sep 28 '22 08:09

Siddharth Rout