我是VBA的新手,如果你们中的任何一个很友好的话,我需要一些基本代码方面的帮助。
当给定单元格中的计算结果> 20%或<-20%时,我试图创建一个Msgbox进行填充。
当值大于20%(例如36%)时,我可以填充一个Msgbox。但是,当我尝试使代码对<-20%(例如-49%)执行相同操作时,将不会加载提示框。我尝试过多种代码变体,但是运气不佳。
这很不错:
Sub Worksheet_Change(ByVal Target As Range)
Dim xCell As Range, Rg As Range
On Error Resume Next
Set Rg = Application.Intersect(Target, Range("P27"))
If Not Rg Is Nothing Then
For Each xCell In Rg
If xCell.Value >= "0.2" Then
VBA.MsgBox "You have exceeded the reportable reconciliation limit of +/- 20%." & VBA.Constants.vbNewLine & "Please email sales@XXXX " _
, vbOKOnly, "IMPORTANT MESSAGE"
Exit Sub
End If
Next
End If
End Sub
没有什么
Sub Worksheet_Change(ByVal Target As Range)
Dim xCell As Range, Rg As Range
On Error Resume Next
Set Rg = Application.Intersect(Target, Range("P27"))
If Not Rg Is Nothing Then
For Each xCell In Rg
If xCell.Value <= "-0.2" Then 'This part is not executed properly
VBA.MsgBox "You have exceeded the reportable reconciliation limit of +/- 20%." & VBA.Constants.vbNewLine & "Please email sales@XXXX " _
, vbOKOnly, "IMPORTANT MESSAGE"
Exit Sub
End If
Next
End If
End Sub
实际上,当我尝试将代码用于任何<20,即If xCell.Value <= "-0.2"
时,则不会填充Msgbox。
答案 0 :(得分:0)
您使用的是字符串值而不是数字,请尝试使用If xCell.Value <= -0.2 Then
。
另外,您可以将in和ifelse语句结合在一起:
If xCell.Value >= 0.2 Then
VBA.MsgBox "You have exceeded the reportable reconciliation limit of +/- 20%." & VBA.Constants.vbNewLine & "Please email sales@XXXX " _
, vbOKOnly, "IMPORTANT MESSAGE"
ElseIf xCell.Value <= -0.2 Then
VBA.MsgBox "You have exceeded the reportable reconciliation limit of +/- 20%." & VBA.Constants.vbNewLine & "Please email sales@XXXX " _
, vbOKOnly, "IMPORTANT MESSAGE"
End if