2017-08-22 65 views
1

下午好,我想借助Sheet1.Range(「I15:I18」)中改變的單元值宏函數 來引入基於Vlookup函數的文本值,避免使用公式。這是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

您不要在'Worksheet.Change'代碼 –

+0

定義變量'Num'而應指定的表'範圍(Target.Address)'屬於,只是避免任何問題。 –

+0

謝謝。我如何可以定義數字例如? – Tom

回答

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 
+0

請參閱我的編輯 - 缺少一個'結束如果' –

+0

非常感謝蒂姆,已經嘗試過它,它的工作完美。我還問你還有一個忙嗎?我想添加一個日期與您的程序target.offset(0,2)我想添加一個基於Vlookup的日期:如果低風險日期+ 180如果中等風險日期+ 150高風險日期+ 120.請讓我知道如果有可能的。非常感謝 – Tom

+0

如何確定風險? –