需求
在Excel中實現監控兩個單元格之間的變化范圍,當達到某個設定的值的范圍內時,實現自動響鈴提示。
實現:
- 首先設置Excel,開啟宏、打開開發者工具,點擊visual Basic按鈕
,然后在左側雙擊需要監測的sheet。
- 此時會打開一個代碼編輯窗口,在窗口中粘貼代碼,修改需要監控的單元格,然后保存。
- 將響鈴用的wav格式文件放入到D盤,以下以D盤為例,可自定義。
- 此時回到Excel頁面然后在對應的單元格編輯數字進行測試。
- 以下代碼實現了A1到B10這一組范圍的多個單元格對,當有一個有變化達到條件時即可出發響鈴。
Private Declare PtrSafe Function PlaySound Lib "winmm.dll" Alias "PlaySoundA" _(ByVal pszSound As String, ByVal hmod As Long, ByVal fdwSound As Long) As Long' 常量定義
Private Const SND_ASYNC = &H1 ' 異步播放(后臺播放)
Private Const SND_FILENAME = &H20000 ' 參數是文件名
Private Const SND_NODEFAULT = &H2 ' 找不到文件時不播放默認聲音' 模塊級變量,用于記錄已觸發過的行和對應的值
Private triggeredRows As ObjectPrivate Sub Worksheet_Activate()' 初始化字典,在工作表激活時執行一次If triggeredRows Is Nothing ThenSet triggeredRows = CreateObject("Scripting.Dictionary")End If
End SubPrivate Sub Worksheet_Calculate()Dim i As LongDim threshold As DoubleDim soundFile As StringDim valA As Variant, valB As VariantDim diff As DoubleDim key As StringDim currentHash As String' 設置參數threshold = 2 ' 閾值soundFile = "D:\xm3555.wav" ' WAV 文件路徑' 初始化 DictionaryIf triggeredRows Is Nothing Then Set triggeredRows = CreateObject("Scripting.Dictionary")' 遍歷每一行For i = 1 To 10valA = Range("A" & i).ValuevalB = Range("B" & i).Value' 確保都是數字If IsNumeric(valA) And IsNumeric(valB) Thendiff = Abs(valA - valB)' 構造唯一標識符(當前 A 和 B 的值組合)currentHash = valA & "|" & valBkey = "Row" & i' 如果這一行沒有觸發過,或者值發生了變化If Not triggeredRows.Exists(key) Or triggeredRows(key) <> currentHash ThenIf diff < threshold Then' 播放聲音If Dir(soundFile) <> "" ThenPlaySound soundFile, 0, SND_ASYNC Or SND_FILENAME Or SND_NODEFAULTElseMsgBox "警告音文件未找到: " & soundFile, vbExclamationPlaySound vbNullString, 0, SND_ASYNCEnd If' 更新記錄為當前值triggeredRows(key) = currentHashElse' 差值不小于閾值,則清除該行記錄(可選)If triggeredRows.Exists(key) ThentriggeredRows.Remove keyEnd IfEnd IfEnd IfEnd IfNext i
End Sub