如何停止ComboBox1_Click重复触发工作表_Change并弄乱目标地址?

时间:2019-03-05 12:00:35

标签: excel vba

我有一个使用VBA宏的“表单填写”工作表,可以将数据自动移动到另一个“数据库”工作表。然后,有ComboBox可以从数据库中搜索和检索数据。

机制是ComboBox_Click,它将文本值复制到Target.Address,这将触发Worksheet_Change,最后将检索并显示数据。

问题是ComboBox_Click多次触发Worksheet_Change(约3次)并弄乱了指定的Target.Address。如果我在指定的Target之外编辑单元格值,则将触发Worksheet_Change,则每个单元格现在似乎都充当Target.Address。 编辑:目标地址没有弄乱

如何停止此操作?


这是“表单填写”工作表中的VBA代码,是简化的,不是我的代码,我是根据从网站获得的代码进行编辑的。

Option Explicit
----------------------------------------------------
Private Sub ComboBox1_Click()

    Me.Range("myTargetAddress").Value = Me.Range("myComboBoxValue").Value
    'myComboBoxValue is ComboBox LinkedCell property

End Sub
----------------------------------------------------
Private Sub Worksheet_Change(ByVal Target As Range)

    Dim wForm as Worksheet
    Dim wDatabase as Worksheet
    Dim lRowNextEmpty As Long
    Dim lRowLastFilled As Long
    Dim lRowMyDataPosition As Long
    Dim lRowMyDataPostionExact As Long
    Dim rMyDataToFill As Range

    Set rMyDataToFill = wForm.Cells("C3:C12")

    ... 'collapsed to concise

    Application.EnableEvents = False

    Select Case Target.Address
        Case Me.Range("myTargetAddress").Address

        Case Else
        GoTo WaitAndSee
    End Select

    With wDatabase
        lRowNextEmpty = .Cells(.Rows.Count, "B").End(xlUp).Offset(1, 0).Row - 1
        lRowLastFilled = lRowNextEmpty - 1
    End With

    With wDatabase
        lRowMyDataPostion = wForm.Range("A1").Value 'A1 contain formula to match lookup
        If  lRowMyDataPostition > 0 And lRowMyDataPosition <= lRowLastFilled
            lRowMyDataPositionExact = lRowMyDataPosition + 1 '+ 1 to overcome column header
            .Range(.Cells(.lRowMyDataPositionExact, 1), .Cells(lRowMyDataPositionExact, 10).copy
            'this will copy, for excample, A1:J1 from database 'J is the 10th column
            rMyDataToFill.Cells(1,1).PasteSpecial Paste:=xlPasteValues, Transpose:=True
        End If
    End With


WaitAndSee:

    Application.EnableEvents = True
    Exit Sub

End Sub

1 个答案:

答案 0 :(得分:0)

如果您不想在ComboBox1_Click()中触发Worksheet_Change(),则可以通过Application.EnableEvents禁用应用程序事件(请确保稍后启用它)。如果要触发代码,但只触发一次,则可以禁用事件并显式调用该过程:

Private Sub ComboBox1_Click()
    Application.EnableEvents = False

        Me.Range("myTargetAddress").Value = Me.Range("myComboBoxValue").Value
        'myComboBoxValue is ComboBox LinkedCell property

        '''  if you want to call Worksheet_Change() (once), uncomment the next line
        ' Call Worksheet_Change(Target:=Me.Range("myTargetAddress"))

    Application.EnableEvents = True
End Sub