通过Vlookup宏将文本值添加到相邻目标范围

时间:2017-08-22 14:09:53

标签: excel vba excel-vba

下午好,我希望通过更改的单元格值宏功能 在Sheet1.Range(" I15:I18")中引入基于Vlookup函数的文本值,避免使用公式。这是Vlookup函数文本正在查看的表:

    A      B
1   0     Low Risk
2   10    Medium Risk
3   15    High Risk

它遵循代码,它对我不起作用:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range
    Dim num As Long
    Dim sRes As Variant

    Set KeyCells = Sheet1.Range("I15:I18")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
        sRes = Application.VLookup(num, Sheet2.Range("A56:B58"), 2, True)

        Debug.Print sRes
        Sheet1.Target.Offset(0, 1).Text = sRes
    End If
End Sub

该范围内的实际分数由另一个完美运行的宏触发。 这里也遵循可以使用单个单元格正常工作的宏:

Sub NumberVLookup()
    Dim num As Long
    num = 16

    Dim sRes As Variant
    sRes = Application.VLookup(num, Sheet2.Range("A56:B58"), 2, True)

    Debug.Print sRes
    Sheet2.Range("J15") = sRes
End Sub

我非常感谢你在这方面的帮助。

1 个答案:

答案 0 :(得分:1)

未测试:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range
    Dim sRes As Variant

    on error goto haveError

    Set rng = Application.Intersect(Me.Range("I15:I18"), Target)

    If Not rng Is Nothing Then
        If rng.cells.count = 1 then
            sRes = Application.VLookup(rng.Value, _
                   Sheet2.Range("A56:B58"), 2, True)
            'turn off events before updating the worksheet
            Application.enableEvents = False
            rng.Offset(0, 1).Value = IIf(IsError(sRes), "???", sRes)
            Select Case rng.Offset(0, 1).Value
                Case "Low Risk": rng.Offset(0, 2).Value = Date + 180
                Case "Medium Risk": rng.Offset(0, 2).Value = Date + 150
                Case "High Risk": rng.Offset(0, 2).Value = Date + 120
            End Select
            Application.enableEvents = True
        End If '<< edit added missing line here
    End If
    Exit Sub

haveError:
    Application.enableEvents = True '<< ensures events are reset
End Sub