在一次删除/复制/粘贴多个单元格时执行Excel VBA代码

时间:2018-01-17 21:59:11

标签: excel vba excel-vba

当您一次删除或编辑目标列中的多个单元格时,似乎会执行这些代码块。在大多数情况下,用户试图将允许的值粘贴到这些单元格中,一次只能粘贴多个单元格。这导致用户必须处理无缘无故弹出的消息框。有关如何进行相同错误检查的任何想法,但是当您选择或更改多个单元格时没有弹出消息框?此代码粘贴在microsoft excel对象(表单代码)中。

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 14 Then  'COLUMN N
    If Not IsNumeric(Target.Value) Then
        MsgBox "Please enter LBS ran with only numbers.", vbExclamation
        Exit Sub
    End If
    If Len(Target.Value) < 4 And Target.Value <> 0 Then
        MsgBox "Please enter LBS ran with comma included.", vbExclamation
        Exit Sub
    End If
End If

If Target.Column = 15 Then  'COLUMN O
    If Not IsNumeric(Target.Value) Then
        MsgBox "Please enter LBS ran with only numbers.", vbExclamation
        Exit Sub
    End If
    If Len(Target.Value) < 4 And Target.Value <> 0 Then
        MsgBox "Please enter LBS ran with comma included.", vbExclamation
        Exit Sub
    End If
End If


'IF COLUMN Q IS MARKED, BUT NOT COMPLETE TEXT TURNS RED
If Target.Column = 18 Then
    If Target.Value = "YES" Or Target.Value = "Yes" Or Target.Value = "yes" Then 'Marks text green
        With Target.Font
            .Color = -16724992
            .TintAndShade = 0
        End With
    Else
        With Target.Font
            .Color = vbRed
            .TintAndShade = 0
        End With
    End If
End If


End Sub

1 个答案:

答案 0 :(得分:2)

您始终只需检查选择了多少Targets,并在If声明中使用该内容:

If target.Count = 1 Then msgbox("My Message!")

因为这是一个简单的一行If语句,你可以在一行中完成所有操作,而不是说,

If target.Count = 1 Then
    msgbox("My Message!")
End If

而且,查看代码,或许将整个第一部分包含在这样的声明中,因为你所做的只是发出一条信息:

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count = 1 Then ' <-------- Checking how many cells were changed.
    If Target.Column = 14 Then    'COLUMN N
        If Not IsNumeric(Target.Value) Then
            MsgBox "Please enter LBS ran with only numbers.", vbExclamation
            Exit Sub
        End If
        If Len(Target.Value) < 4 And Target.Value <> 0 Then
            MsgBox "Please enter LBS ran with comma included.", vbExclamation
            Exit Sub
        End If
    End If

    If Target.Column = 15 Then    'COLUMN O
        If Not IsNumeric(Target.Value) Then
            MsgBox "Please enter LBS ran with only numbers.", vbExclamation
            Exit Sub
        End If
        If Len(Target.Value) < 4 And Target.Value <> 0 Then
            MsgBox "Please enter LBS ran with comma included.", vbExclamation
            Exit Sub
        End If
    End If
End If 'Target.Count = 1 

'IF COLUMN Q IS MARKED, BUT NOT COMPLETE TEXT TURNS RED
' << Rest of your code here >>