当我删除数据时,代码将卡住

时间:2018-03-07 13:25:10

标签: excel vba excel-vba vlookup

我有excel工作表和下拉列表,当我从列表中选择任何内容时 enter image description here

宏将vlookup请求值。但是,当我想从这些单元格中删除值时,我选择它们并按删除键,它会显示我" #N / A"并且excel被冻结了,我什么都做不了。你能告诉我,我怎么能避免它,拜托? enter image description here

Option Explicit

Private Sub Worksheet_Change()
    Dim Target As Range
    Dim selectedNa As Integer, selectedNum As Integer

    selectedNa = Target.Value
    If Target.Column = 10 Then
        selectedNum = Application.VLookup(selectedNa, ActiveSheet.Range("dropdown"), 2, False)
        If Not IsError(selectedNum) Then
            Target.Value = selectedNum
        Else: Exit Sub
        End If
    Else: Exit Sub
    End If
End Sub

3 个答案:

答案 0 :(得分:1)

尝试以下方法:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

 Dim selectedNa As Long, selectedNum As Variant

 If Target.Column = 10 And Not IsEmpty(Target) Then  'selectedNa <> vbNullString Then '

    Application.EnableEvents = False

    On Error GoTo errhand

    selectedNa = Target.Value

    selectedNum = Application.VLookup(selectedNa, ActiveSheet.Range("dropdown"), 2, False)

     If Not IsError(selectedNum) Then

         Target.Value = selectedNum

     End If

     Application.EnableEvents = True

 End If

 Exit Sub

errhand:
If Err.Number <> 0 Then
    Application.EnableEvents = True
End If

End Sub

答案 1 :(得分:0)

将发布的代码更改为

Option Explicit
Private Sub Worksheet_Change(ByVal target As Range)

Dim selectedNa As Integer, selectedNum As Integer

    On Error GoTo EH

    Application.EnableEvents = False

    selectedNa = target.Value

    If target.Column = 10 Then
        selectedNum = Application.VLookup(selectedNa, ActiveSheet.Range("dropdown"), 2, False)
        If Not IsError(selectedNum) Then
            target.Value = selectedNum
        End If
    End If

EH:
    Application.EnableEvents = True
    Debug.Print Err.Number, Err.Description
End Sub

代码必须放入图纸模块。 更改或删除工作表中的值后,请查看即时窗口。

答案 2 :(得分:0)

根据提供的信息, 看起来就像你想要的那样:

def