我在用户窗体上有一个列表框,该列表框具有我要通过提供用户窗体中的值来覆盖的源范围,但是一旦我覆盖特定单元格,就会触发事件ListBox1_Click()
,这在重新填充时是不可取的用户表单上的数据。
Private Sub ListBox1_Click()
Application.EnableEvents = False
Dim i As Long, fRow As Long
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then
If i > 0 Then
HSht.Range("cRow").Value = i + 1
fRow = HSht.Range("cRow").Value
Call getData(fRow)
HSht.Range("LRow").Value = getlastRow()
Me.ItemLbl.Caption = "Item number :" & HSht.Range("cRow").Value - 1 & " of " & HSht.Range("LRow").Value - 1
End If
Exit For
End If
Next i
Application.EnableEvents = True
End Sub
这是更新按钮代码:
Private Sub cmdUpdate_Click()
Application.EnableEvents = False
'Update
Dim fRow As Long, i As Long
fRow = HSht.Range("cRow").Value
Call updateData(fRow)
HSht.Range("LRow").Value = getlastRow()
Me.ItemLbl.Caption = "Item number :" & HSht.Range("cRow").Value - 1 & " of " & HSht.Range("LRow").Value - 1
'MsgBox "Data updated successfully"
Application.EnableEvents = True
End Sub
例如,假设您有10个字段,并且用户窗体上有10个文本框用于查看/修改数据,但是当我向上或向下滚动时,也可以使用多列列表框以表格格式查看和滚动数据在userform的文本框中排行数据,如果我想通过userform修改工作表上的数据,我还有一个按钮“覆盖”。但是,一旦修改工作表中的一个单元格,就会触发“ Listbox1_click”事件,并覆盖用户窗体上的数据。
答案 0 :(得分:2)
Application.EnableEvents = false
won't affect UserForms
。如果事件被禁用,您必须创建一个属性并在事件开始和退出事件子处检查其值:
' Top of UserForm-Class
Public EnableEvents As Boolean ' if Private code outside the userform can't change value.
'One should add a Letter/Getter to have more control over the property (exposing the variable that stores a property-value isn't recommended I think, with Get/Let we can perform checks or just make the Letter private, but the Getter public)
Private Sub UserForm_Initialize()
Me.EnableEvents = True
End Sub
Private Sub ListBox1_Click()
If Me.EnableEvents = False Then 'the first three lines of code suppress the events-code execution if EnableEvents = False and must be on top of every event that you want to have disabled.
Exit Sub
End If
'Me.EnableEvents = False should be set on top of button code and Me.EnableEvents = True at buttom if other events of from should be suppressed.
Dim i As Long, fRow As Long
For i = 0 To ListBox1.ListCount - 1
...
End Sub
Private Sub cmdUpdate_Click()
If Me.EnableEvents = False Then 'the first three lines of code suppress the events-code execution and must be on top of every event that you want to have disabled.
Exit Sub
End If
Me.EnableEvents = False 'disable Form-Events
... 'Button-Code
Me.EnableEvents = True 'reenable events
End Sub