使用 Worksheet_Change 事件,您可以执行以下操作,这假设您的数据验证列表位于单元格 B1 中,并且您希望结果位于 C1 中:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
Dim CustomNumber As Variant
If Target.Address = "$B$1" Then
Select Case ws.Range("B1").Value
Case "A"
ws.Range("C1").Formula = "=1+1"
Case "B"
ws.Range("C1").Formual = "=1+2"
Case "C"
ws.Range("C1").Formula = "=1+3"
Case "D"
ws.Range("C1").Formula = "=1+4"
Case "E"
ws.Range("C1").Formula = "=1+5"
Case "Custom"
CustomNumber = InputBox("Please enter a custom number", "Custom")
If IsNumeric(CustomNumber) Then
ws.Range("C1").Formula = "=1+" & CustomNumber
Else
MsgBox "Please enter a number", vbCritical = vbOKOnly
Exit Sub
End If
End Select
End If
End Sub
编辑:
根据 cmets,我已将答案更新为只有两个案例,使用自定义数字或使用公式返回的值,这假设您的查找公式在 A1 中,根据需要修改您的代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
Dim CustomNumber As Variant
If Target.Address = "$B$1" Then
Select Case ws.Range("B1").Value
Case "Custom"
CustomNumber = InputBox("Please enter a custom number", "Custom")
If IsNumeric(CustomNumber) Then
ws.Range("C1").Formula = "=1+" & CustomNumber
Else
MsgBox "Please enter a number", vbCritical = vbOKOnly
Exit Sub
End If
Case Else 'if your lookup formula is in A1, then the code below will add one to the value from the formula
ws.Range("C1").Formula = "=1+" & Val(ws.Range("A1").Value)
End Select
End If
End Sub
更新:
在 OP 的进一步 cmets 之后,我更新了代码以包含公式返回的查找值:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
Dim CustomNumber As Variant
If Target.Address = "$B$1" Then
Select Case ws.Range("B1").Value
Case "Custom"
CustomNumber = InputBox("Please enter a custom number", "Custom")
If IsNumeric(CustomNumber) Then
ws.Range("C1").Formula = "=1+" & CustomNumber
Else
MsgBox "Please enter a number", vbCritical = vbOKOnly
Exit Sub
End If
Case Else 'if your lookup formula is in A1, then the code below will add one to the value returned by the LookUp
LookUpValue = "Ground type"
LookUpTable = "Ground_type_table[#Alle]"
ValueReturned = Application.WorksheetFunction.VLookup(LookUpValue, LookUpTable, 4, False)
ws.Range("C1").Formula = "=1+" & Val(ValueReturned)
End Select
End If
End Sub