簡體   English   中英

只顯示一次 MsgBox

[英]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

執行后, readFalse初始化,然后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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM