[英]Show MsgBox only once
我有一個 VBA 腳本,內容如下:
1, it will run when particular sheet is selected
2、判斷條件是否為真
3、如果有,顯示MsgBox
Private Sub Worksheet_Activate()
Dim current As Double
current = Round(((Range("AJ9").Value / Range("AG9").Value) * 100), 1)
If Range("AJ9").Value / Range("AG9").Value < 0.15 Then
MsgBox "Here is some message and some value: " & current & "%."
End If
End Sub
當用戶來到工作表時,我只想第一次顯示這個 MsgBox。 現在每次用戶訪問工作表時它都會彈出。 我曾嘗試使用來自不同 Sub 的變量,但它似乎不起作用。
Public read As Boolean
Sub readValue(Optional readArg As Boolean)
MsgBox readArg
read = (readArg Or False)
End Sub
然后我像這樣修改了第一個 Sub:
Private Sub Worksheet_Activate()
Dim current As Double
current = Round(((Range("AJ9").Value / Range("AG9").Value) * 100), 1)
Call readValue
If read = False Then
If Range("AJ9").Value / Range("AG9").Value < 0.15 Then
MsgBox "Here is some message and some value: " & current & "%."
readValue read = True
End If
End If
但是MsgBox readArg
總是說False
。 就好像它根本沒有發送價值。 因此,MsgBox 顯示每次用戶來到工作表。
我究竟做錯了什么?
對Optional
參數的ByRef
分配使機制相當脆弱,並且標志不需要是Public
。
執行后, read
用False
初始化,然后Activate
處理程序最終運行; readValue
沒有為其可選參數指定默認值,因此第一次調用( Call readValue
,...注意Call
是多余的)會彈出一個顯示“False”的 msgbox,然后read = (readArg Or False)
計算結果為False
...並且存在錯誤,因為此時您需要標志為True
- unconditionally 。
你在正確的軌道上,但它可以比這更簡單:
Option Explicit
Private alreadyPrompted As Boolean
Private Sub Worksheet_Activate()
If alreadyPrompted Then Exit Sub
If Range("AJ9").Value / Range("AG9").Value < 0.15 Then
Dim current As Double
current = Round(((Range("AJ9").Value / Range("AG9").Value) * 100), 1)
MsgBox "Here is some message and some value: " & current & "%."
alreadyPrompted = True
End If
End Sub
另一種方法是將標志Static
本地; 這樣的聲明在過程調用之間保留了它們的價值——但要小心不要濫用它,因為這很容易讓人混淆:
Option Explicit
Private Sub Worksheet_Activate()
Static alreadyPrompted As Boolean
If alreadyPrompted Then Exit Sub
If Range("AJ9").Value / Range("AG9").Value < 0.15 Then
Dim current As Double
current = Round(((Range("AJ9").Value / Range("AG9").Value) * 100), 1)
MsgBox "Here is some message and some value: " & current & "%."
alreadyPrompted = True
End If
End Sub
請注意,我在兩個片段中都對current
條件進行了計算,因為如果條件不正確,則不需要計算變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.