我需要一些帮助来创建 Excel VBA 以在计算单元格(其中包含公式的单元格)的任何输入范围发生更改并满足该范围的给定标准时显示消息框。
例如,范围“B2”包含作为“A2”函数的计算单元格,如果在更新输入“A2”时,重新计算的单元格“B2”超过 20%,我想警告用户一个消息框。
UPDATE
This code will only trigger if your input cells change, which is better than just using 'Worksheet_Calulate`:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim myRange As Range
myRange = Range("B1:B2") '-> assumes input cells are in B1:B2
If Intersect(myRange, Target) Then
'-> assumes calculated cell in A1
If Range("A1").Value > 0.2 Then MsgBox "Above 20%"
'-> to loop through many cells, do this
Dim cel As Range
For Each cel In Range("A1:A10")
If cel.Value > 0.2 Then MsgBox cel.Address & " Above 20%"
Exit For
Next
End If
End Sub
编辑:斯科特让我想起Intersect
了比这个功能更好的InRange
功能
Edit2:这将允许您对不同的范围有不同的规则。如果用户更改的单元格在您的控制范围之一内,则调用该范围的验证规则。否则功能继续。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Range1 As Range, Range2 As Range '...
Set Range1 = Me.Range("A1:A9")
Set Range2 = Me.Range("B1:B9")
'...
If Not intersect(Range1, Target) Is Nothing Then
'Rule for Range1
If Target.Value > 0.2 Then 'put your condition here
MsgBox "You exceeded 20%"
End If
ElseIf intersect(Range2, Target) Is Nothing Then
'Rule for Range2...
'elseif more ranges...
'More rules...
End If
End Sub
这是使用工作簿工作表更改事件的示例,该事件检查工作表 1 中 A1 单元格中的更改
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
On Error Resume Next
'check to ensure we are working in the correct Sheet
If ActiveWorkbook.ActiveSheet.Name = "Sheet1" Then
'check to see how many cells have been targeted
If Target.Cells.Count = 1 Then
If Target.Cells.Address = "$A$1" Then
'check to see what value has been entered into the cell
If Target.Value = 20 Then
MsgBox "Alerting the user"
End If
End If
End If
End If
End Sub