更新命名范围内的特定值?

Update specific value in named range?

我有以下从命名范围中检索值的函数:

Function getSetting(settingName As String)
    getSetting = Application.VLookup(settingName, Range("rSettings"), 2, True)
End Function

现在我可以轻松地说 myColor = getSetting("myColor") 并且它会 return "blue" 或其他。

我现在要做的是更新那个值。

Function updateSetting(settingName As String, newValue As String)
    ?????
End Function

想法?

你需要使用一个 sub 而不是函数。

二你可以使用Range.Find方法来查找单元格。然后用offset改值。

Sub updateSetting(settingName As String, newValue As String)
    Dim c As Range
    Set c = Range("rSettings").Find(settingName)
    c.Offset(, 1).Value = newValue
End Sub

还有你的第一个函数,个人喜好是可以用vba函数的地方不要用worksheet函数。比较慢。

Function getSetting(settingName As String)
     Dim c As Range
    Set c = Range("rSettings").Find(settingName)
    getSetting = c.Offset(, 1).Value 
End Function

您可以使用匹配函数确定范围内每个 settingName 的位置:

WorksheetFunction.Match method

Returns the relative position of an item in an array (array: Used to build single formulas that produce multiple results or that operate on a group of arguments that are arranged in rows and columns. An array range shares a common formula; an array constant is a group of constants used as an argument.) that matches a specified value in a specified order. Use MATCH instead of one of the LOOKUP functions when you need the position of an item in a range instead of the item itself.

dim index
index = Match(settingName,Range("settings"),0)