Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using named cells in a VBA function

I have a worksheet where I have defined names for certain cells. These cells will be used in the function and I am calling them using their names.

However, I get 0 as a return of the function when I call it with Excel, as if the names were not linked or had a 0 value.

Below is the code I wrote. "Sum_Len_1", "L_W_2" ans "L_W_1" are the names I gave to the source cells.

Function min_w(depth)

    If depth < Sum_Len_1 Then
        min_w = L_W_1 * 0.868 * depth / 1000
    Else
        min_w = L_W_1 * 0.868 * Sum_Len_1 / 1000 + L_W_2 * 0.868 * (depth - Sum_Len_1) / 1000
    End If

End Function

How can I solve the problem?

like image 337
user2453446 Avatar asked Jun 21 '13 10:06

user2453446


People also ask

How do you reference a named cell in Excel VBA?

If the Excel VBA Range object you want to refer to is a single cell, the syntax is simply “Range(“Cell”)”. For example, if you want to make reference to a single cell, such as A1, type “Range(“A1″)”.

Can I use named range in VBA?

Named Ranges are the name given for a group or range of cells. Named range is used to refer to the specific range of cells which needs to be accessed later on. We can name a range in both excel or VBA. While making a named range in VBA we need to use Add name function in VBA.

How do you reference a named range in Excel VBA?

Refer to this named range by just the name in the same worksheet, but from another worksheet you must use the worksheet name including "!" the name of the range (example: the range "Name" "=Sheet1! Name").

Can you use defined Names in VBA?

Using Defined Names in VBA code is different than using them in worksheet cells. You must get the value of the Name using the RefersTo or RefersToRange properties. If a Name doesn't refer to a cell or range of cells (e.g., it refers to a constant), an attempt to use RefersToRange will fail.


2 Answers

If you just write min_w = L_W_1 * 0.868 * depth / 1000 vba thinks L_W_1 it's variable (of the type variant with value=0). You have to do it like this Range("L_W_1").Value to reference the named cell.

It should work if you change it to:

Function min_w(depth As Long)
If depth < Range("SUM_LEN_1").Value Then
    min_w = Range("L_W_1").Value * 0.868 * depth / 1000
Else
    min_w = Range("L_W_1").Value * 0.868 * Range("SUM_LEN_1").Value / 1000 + Range("L_W_2").Value * 0.868 * (depth - Range("SUM_LEN_1").Value) / 1000
End If
End Function
like image 69
MiVoth Avatar answered Sep 30 '22 16:09

MiVoth


You can just put them in brackets to mark them as a range: [Sum_Len_1].Value, [L_W_2].Value and [L_W_1].Value

like image 25
robotik Avatar answered Sep 30 '22 17:09

robotik