简体   繁体   English

Excel VBA VLOOKUP #VALUE错误中的命名范围

[英]Excel VBA Named Range in VLOOKUP #VALUE error

This code throws a #VALUE error in cell A8 or A17 (depending on which toggle is active) instead of the string value from the 'dataWeaponField' named range. 这段代码在单元格A8或A17中(取决于激活的是哪个切换)引发#VALUE错误,而不是来自“ dataWeaponField”命名范围的字符串值。 This Excel formula in (for example) cell A17 works correctly: =VLOOKUP(B17,dataWeaponField,2,FALSE). (例如)单元格A17中的此Excel公式正常工作:= VLOOKUP(B17,dataWeaponField,2,FALSE)。 I am trying to simply replicate this formula in VBA. 我试图简单地在VBA中复制此公式。

Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
    If Target.Column = 1 And Target.Row = 7 Then 'CLICK TO SWAP WEAPONS
        If Range("A8").Interior.ColorIndex = 6 Then 'Primary Weapon
            Range("A8:C15").Interior.ColorIndex = 12 'Primary Weapon
            Range("A17:C24").Interior.ColorIndex = 6 'Secondary Weapon
            Range("A8").Value = "" 'Primary Weapon
            Range("A17").Value = Application.VLookup(Range("B17"), ThisWorkbook.Names("dataWeaponField"), 2, False)
        Else
            Range("A8:C15").Interior.ColorIndex = 6 'Primary Weapon
            Range("A17:C24").Interior.ColorIndex = 12 'Secondary Weapon
            Range("A8").Value = Application.VLookup(Range("B8"), ThisWorkbook.Names("dataWeaponField"), 2, False)
            Range("A17").Value = "" 'Secondary Weapon
        End If
        Range("A6").Select 'Cell above CLICK TO SWAP WEAPONS
    End If
End Sub

Because you are passing a Name object instead of Range . 因为您要传递Name对象而不是Range You can set the Formula: 您可以设置公式:

Range("A17").Formula = "=VLOOKUP(B17, dataWeaponField, 2, FALSE)"

or Evaluate it: 评估

Range("A17").Value = [VLOOKUP(B17, dataWeaponField, 2, FALSE)]

Also, because SelectionChange doesn't trigger when clicking a selected cell, you can use a Control or Hyperlink and the Worksheet.FollowHyperlink Event 此外,由于在单击选定的单元格时不会触发SelectionChange ,因此可以使用Control或Hyperlink和Worksheet.FollowHyperlink事件

ThisWorkbook.Names("dataWeaponField") is a Name object, not a Range object. ThisWorkbook.Names("dataWeaponField")是一个Name对象,而不是Range对象。 VLookup expects the latter, so you can simply replace this expression by Application.Range("dataWeaponField") . VLookup期望使用后者,因此您只需将其替换为Application.Range("dataWeaponField")

The Application. Application. prefix is necessary because your code is in a worksheet code module, and the named range belongs to another worksheet, so we need the application object to fetch it from global scope. 前缀是必需的,因为您的代码在工作表代码模块中,并且命名范围属于另一个工作表,因此我们需要应用程序对象从全局范围中获取它。

Alternatively you can evaluate the whole formula that works in Excel as is, using Application.Evaluate(yourWorkingFormula) . 或者,您可以使用Application.Evaluate(yourWorkingFormula)评估可在Excel中正常使用的整个公式。

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

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