简体   繁体   中英

Assign value based on named range/cell

I want to assign current cell value based on current cell name.

For example, (see worksheet image) cell B3 has assigned name "ABC", B4 assigned name "EFG", B5 assigned name "XYZ", I want cells B3:B5 to automatically pick up corresponding value from table in column D:E.

样本

So what I came up with is:

Step 1. identify name of current cell using UDF

Function cell_name() As String
Dim rng As Range
On Error Resume Next
Set rng = ActiveCell
If Len(rng.Name.Name) < 0 Then
   cell_name = "No named Range"
   Exit Function
End If
cell_name = rng.Name.Name
If InStr("cell_name", "!") > 0 Then
   cell_name = Right(cell_name, Len(cell_name) - InStr(cell_name, "!"))
End If
End Function

**I didn't came up with VBA codes above, credit goes to this post: https://superuser.com/questions/683825/formula-return-cell-defined-name

Step 2. Vlookup using cell_name from step 1 above

cell formula in B3 to B5 =VLOOKUP(cell_name(),$D$3:$E$8,2,FALSE)

By applying above two steps, individual cell does return value as expected, HOWEVER, whenever any values changed in the worksheet, such as change value in cell E7 from 500 to 5000, or insert new line, the calculation breaks and resulting #N/As in B3:B5

I tried Application.Volatile, but didn't work.

I also tried force recalculate cells with macro, but didn't work as expected neither.

Sub Force_Recalc()
    Cells.Replace What:="=", Replacement:="=", LookAt:=xlPart, SearchOrder _
        :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
End Sub

Any recommendations? either improve my existing functions to work as expected, or a smarter way to achieve what I want to do.

Thank you!

In cell_name() , use Application.Caller instead of ActiveCell .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM