رخداد Change زمانی رخ میدهد که سلولهای کاربرگ توسط کاربر یا یک پیوند خارجی تغییر میکند.
دستور اجرا
expression.Change (Target)
expression متغیری است که یک شی Worksheet را نمایندگی میکند.
پارامترها
نام | اجباری/اختیاری | نوع داده | توضیحات |
---|---|---|---|
Target | اجباری | Range | محدوده تغییر یافته؛ می تواند بیش از یک سلول باشد. |
مقدار بازگشتی
ندارد.
ملاحظات
رخداد Change هنگامی که مقدار سلولها در طول محاسبه مجدد تغییر میکند، رخ نمیدهد. برای این منظور باید از رویداد Calculate برای فعال کردن محاسبه مجدد کاربرگ استفاده نمایید.
ویدئوی آموزشی
مثال
کد زیر با استفاده از رخداد Change مقادیر ورودی کاربر را اعتبارسنجی میکند و در صورت لزوم با ایجاد یک کامنت هشدار لازم را به کاربر ارسال میکند.
Private Sub Worksheet_Change(ByVal Target As Range) Dim boolCheck As Boolean Dim strMessage As String Dim rngCell As Range ' Clear existing formats and comments Target.Interior.Pattern = xlNone Target.ClearComments Target.Font.Color = vbBlack ' Exit if more than one cell is changed or if the cell is empty If Target.Cells.Count > 1 Then Exit Sub If Target.Value = "" Then Exit Sub boolCheck = False ' Check if Target is within the specific ranges and validate If Not Application.Intersect(Target, Me.Range("A2:A10")) Is Nothing Then strMessage = "Please fill the Cell with a valid name" If Not Target.Value Like "[A-Za-z ]*" Then boolCheck = True End If ElseIf Not Application.Intersect(Target, Me.Range("B2:B10")) Is Nothing Then strMessage = "Employee ID must be ten digits long" If Not Target.Value Like "[0-9]*" Or Len(Target.Value) <> 10 Then boolCheck = True End If ElseIf Not Application.Intersect(Target, Me.Range("C2:C10")) Is Nothing Then strMessage = "The salary month must be a number between 1 and 12" If Not Target.Value Like "[0-9]*" Or CInt(Target.Value) < 1 Or CInt(Target.Value) > 12 Then boolCheck = True End If ElseIf Not Application.Intersect(Target, Me.Range("D2:D10")) Is Nothing Then strMessage = "Activity days must be a number between 0 and 31" If Not Target.Value Like "[0-9]*" Or CInt(Target.Value) < 0 Or CInt(Target.Value) > 31 Then boolCheck = True End If End If ' If validation fails, add comment and change formatting If boolCheck Then Target.AddComment strMessage Target.Interior.Color = vbRed Target.Font.Color = vbWhite End If
End Sub