excel 根据输入值更改单元格的值

wkyowqbh  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(170)
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("d10:e309")) Is Nothing Then
        On Error GoTo bm_Safe_Exit
        Application.EnableEvents = False
        With Range("d10:e309")
            Select Case .Value2
                Case 0
                    'do nothing
                Case 1
                    .Value = 0.01
                Case 5
                    .Value = 0.005
            End Select
        End With
    End If

bm_Safe_Exit:
        Application.EnableEvents = True
End Sub

我希望代码在输入到单元格时使用1和5作为快捷方式,以便在分别输入为.01和.005的单元格中自动替换

8tntrjer

8tntrjer1#

Range("d10:e309").Value2将是一个数组。将数组与值进行比较是无效的。其次,如果多个单元格被更改(例如通过复制粘贴),Target.Value也可能是一个数组。它还可能包括您感兴趣范围之外的单元格

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim TargetRange As Range, rng As Range 
    Set TargetRange = Intersect(Target, Range("d10:e309"))
    If Not TargetRange Is Nothing Then
        On Error GoTo bm_Safe_Exit
        Application.EnableEvents = False
        For Each rng In TargetRange 
            Select Case rng.Value2
                Case 0
                    'do nothing
                Case 1
                    Rng.Value = 0.01
                Case 5
                    Rng.Value = 0.005
            End Select
        Next
    End If

bm_Safe_Exit:
    Application.EnableEvents = True
End Sub

相关问题