简体   繁体   English

根据命名范围/单元格分配值

[英]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.例如,(参见工作表图像)单元格 B3 分配了名称“ABC”,B4 分配了名称“EFG”,B5 分配了名称“XYZ”,我希望单元格 B3:B5 自动从 D:E 列中的表中获取相应的值.

样本

So what I came up with is:所以我想出的是:

Step 1. identify name of current cell using UDF步骤 1. 使用 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 **我没有想出上面的 VBA 代码,归功于这篇文章: https://superuser.com/questions/683825/formula-return-cell-defined-name

Step 2. Vlookup using cell_name from step 1 above步骤 2. 使用上述步骤 1 中的 cell_name 进行 Vlookup

cell formula in B3 to B5 =VLOOKUP(cell_name(),$D$3:$E$8,2,FALSE) B3 到 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通过应用上述两个步骤,单个单元格确实按预期返回值,但是,只要工作表中的任何值发生更改,例如将单元格 E7 中的值从 500 更改为 5000,或插入新行,计算就会中断并产生 #N/As在 B3:B5

I tried Application.Volatile, but didn't work.我试过 Application.Volatile,但没有用。

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 .cell_name()中,使用Application.Caller而不是ActiveCell

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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