[英]Visual Basic Excel Color Cells on Lost Focus
我需要在excel中制作一個VBA腳本,當一個值比另一個值大至少10%時,它會為2個單元格上色
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
If Target.Address = aprx_Lns Then
If aprx_Lns > aprx2_Lns * 0.1 Then
aprx_Lns.Interior.Color = Hex(FFFF00)
aprx2_Lns.Interior.Color = Hex(FFFF00)
ElseIf aprx_Lns < aprx2_Lns * 0.1 Then
aprx_Lns.Interior.Color = Hex(FFFF00)
aprx2_Lns.Interior.Color = Hex(FFFF00)
End If
End If
Application.EnableEvents = True
End Sub
Private Sub Worksheet_Change2(ByVal Target As Range)
Application.EnableEvents = False
If Target.Address = aprx2_Lns Then
If aprx_Lns > aprx2_Lns * 0.1 Then
aprx_Lns.Interior.Color = Hex(FFFF00)
aprx2_Lns.Interior.Color = Hex(FFFF00)
ElseIf aprx_Lns < aprx2_Lns * 0.1 Then
aprx_Lns.Interior.Color = Hex(FFFF00)
aprx2_Lns.Interior.Color = Hex(FFFF00)
End If
End If
Application.EnableEvents = True
End Sub
我究竟做錯了什么? 即使在我將值設為if語句為true之后,兩個單元都沒有將顏色更改為所選顏色。
我對VBA幾乎一無所知,因此任何解釋也都很好。 謝謝!
在上面我的評論之后,讓我們將邏輯結合到單個事件處理程序中。
同樣,使用命名的范圍/單元格也很好,但是您需要正確地引用它們。 該名稱本身在VBA中是沒有意義的,除非它被限定為顯式范圍。 將名稱作為字符串傳遞,例如Range("aprx_Lns")
等。
請注意 ,只有直接更改這兩個單元格之一的值時,此代碼才會觸發。 這意味着,如果這些單元格包含引用其他單元格的公式,並且其他單元格發生更改,則不會發生突出顯示。
修訂和簡化
Private Sub Worksheet_Change(ByVal Target As Range)
Dim aprx_Lns As Range
Dim aprx_Lns2 As Range
Dim difference As Double
Dim diffRatio As Double
Set aprx_Lns = Range("aprx_Lns") '## Modify as needed
Set aprx2_Lns = Range("aprx2_Lns") '## Modify as needed
Application.EnableEvents = False
If Target.Address = aprx_Lns.Address Or Target.Address = aprx2_Lns.Address Then
difference = Abs(aprx_Lns) / Abs(aprx2_Lns)
'## compute the absolute difference as a ratio
diffRatio = Abs(1 - difference)
If diffRatio >= 0.1 Then
'### if the cell values differ by +/- 10%, then highlight them
aprx_Lns.Interior.Color = 65535 'vbYellow
aprx2_Lns.Interior.Color = 65535 'vbYellow
Else
'### otherwise, unhighlight them:
aprx_Lns.Interior.Color = xlNone
aprx2_Lns.Interior.Color = xlNone
End If
End If
Application.EnableEvents = True
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.