将特定单元格条件更改为范围条件

时间:2017-11-09 14:22:12

标签: excel vba excel-vba

我想在G1:G500范围内更改单元格(其值等于或大于" 1")时自动运行宏。

我部分成功但是;

  1. 它仅适用于一个特定的细胞。
  2. 我无法写出它是否等于或大于1.只有在单元格值等于1时才有效。
  3. 我真的很抱歉,因为我是VBA的初学者。帮助赞赏。

    请参阅下面的完整代码;

    Private Sub Worksheet_Change(ByVal Target As Range)
    If Intersect(Target, Range("G12")) Is Nothing Then Exit Sub
    If Target = "" Then Exit Sub
    With Application
      .EnableEvents = False
      .ScreenUpdating = False
        If UCase(Me.Range("G12").Value) = "1" Then
    
          Call K999
    
        End If
      .ScreenUpdating = True
      .EnableEvents = True
    End With
    End Sub
    

2 个答案:

答案 0 :(得分:1)

尝试:

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("G1:G500")) Is Nothing Then
    If Target = "" Then Exit Sub
    On Error GoTo GetOut
    With Application
        .EnableEvents = False
        .ScreenUpdating = False
        If Target.Value >= 1 Then
            Call K999
        End If
    End With
End If
GetOut:
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub

答案 1 :(得分:0)

Private Sub Worksheet_Change(ByVal Target As Range)
    '[1]
    If Intersect(Target, Range("G1:G500")) Is Nothing Then Exit Sub
    If Target = "" Then Exit Sub
    '[2]
    If Not IsNumeric(Target.Value) Then Exit Sub
    With Application
        .EnableEvents = False
        .ScreenUpdating = False
        '[3]
        If Target.Value >= 1 Then
            Call K999
        End If
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End Sub
  1. Intersect(Target, Range("G12"))检查目标是否为G12,根据您的说法,它应该是Range(“G1:G500”)

  2. 由于您无法强制用户在单元格中键入数字,因此首先检查值是否为数字会更安全。

  3. “1”是一个字符串,1是一个数字。无需转换为字符串然后比较两个字符串。

相关问题