【问题标题】:Add text value to adjacent target range via Vlookup macro通过 Vlookup 宏将文本值添加到相邻的目标范围
【发布时间】:2017-08-23 05:45:49
【问题描述】:

下午好,我想通过更改单元格值宏功能 在 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

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

【问题讨论】:

  • 你没有在Worksheet.Change代码中定义变量Num
  • 你应该指定Range(Target.Address)属于哪个工作表,以避免任何问题。
  • 谢谢。例如,我该如何定义 num?
  • 工作表为 sheet1。之后你认为代码会运行吗?
  • 在第二个过程中设置Num=16Num 在第一个过程中没有任何价值。

标签: vba excel


【解决方案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

【讨论】:

  • 非常感谢蒂姆,已经尝试过了,效果很好。我还要请你帮个忙吗?我想将您的程序的日期添加到 target.offset (0,2) 我想添加一个基于 Vlookup 的日期:如果低风险日期+180 如果中等风险日期+150 高风险日期+120。请让我知道是否有可能的。非常感谢
  • 风险如何确定?
  • 被小桌子贴出来
  • A B 1 0 低风险 2 10 中等风险 3 15 高风险
  • 0-9 低风险;10-14 中等风险;>=15 高风险
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多