我在用户窗体上有一个列表框,其中有一个源范围,我试图通过提供用户窗体中的值来覆盖该源范围,但是一旦我覆盖特定单元格,就会触发事件 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 个文本框来查看/修改数据,但您还有多列列表框来以表格格式查看和滚动数据,当我向上或向下滚动时,我会得到特定的用户窗体上的文本框中的行数据,我还有一个按钮,上面写着“覆盖”,以防我想通过用户窗体修改工作表上的数据。但一旦它修改了工作表中的一个单元格,事件“Listbox1_click”就会触发,并覆盖用户窗体上的数据。
最佳答案
Application.EnableEvents = false
won't affect 用户表单
。您必须创建一个属性,并在事件开始时检查它的值,如果事件被禁用,则退出事件子,例如:
' 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
关于excel - 覆盖列表框源范围内的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52902292/