Visual Basic for Applications/避免更改事件遞迴
外觀
- 此 VBA 程式碼旨在在可以執行宏的 Microsoft Office 應用程式中執行,例如 Excel 或 Word。
- 它提供了兩個不同的文字框更改事件示例,一個用於 TextBox1,另一個用於 TextBox2。
- 需要注意的是,在顯示錶單並在 TextBox1 中輸入一個字元後,在那裡找到的數字約為 290;這是程式碼顯示已發生的更改事件的迭代次數。
- 在 TextBox2 中執行相同的操作顯示該事件只運行了一次。
- TextBox2_Change 事件的程式碼避免了該過程的多次執行,從而避免了在某些情況下出現錯誤結果的可能性。
'...............................................
' Notes: Code needs a user form named UserForm1,
' with two text boxes, TextBox1 and Textbox2,
'...............................................
Private Sub Workbook_Open()
'Runs on opening the workbook
Load UserForm1
UserForm1.Show
End Sub
Private Sub TextBox1_Change()
' This Change event runs about 294 times
' for each character entered
Static nC As Long
'yield to commands-just in case
DoEvents
'increment for each iteration
nC = nC + 1
'this line causes this procedure to run again
TextBox1.Value = nC
End Sub
Private Sub TextBox2_Change()
' This Change event runs only once
' for each character entered
Static nC As Long
Static bEnableEvents As Boolean
'yield to commands-just in case
DoEvents
' increment for each iteration
nC = nC + 1
' false to start then true after that
If bEnableEvents = True Then
Exit Sub
End If
bEnableEvents = True
' this runs only once
TextBox2.Value = nC
' reset flag
bEnableEvents = False
End Sub