按下空格或选择更多单元格时发生错误:“运行时错误13,键入:不匹配”

时间:2018-08-29 10:26:56

标签: excel vba

我的宏将多个值添加到选定的单元格。

清除一个或多个单元格(按空格时)或选择多个单元格时,出现错误:

  

运行时错误13,键入:不匹配

Option Explicit

Public x

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Interior.ColorIndex <> 35 Then Exit Sub

    Application.EnableEvents = False
    Target = Target + x

    Application.EnableEvents = True
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    x = Target
End Sub

1 个答案:

答案 0 :(得分:0)

假设您要维护在每个浅绿色单元格中输入的值的增量总和...

您需要处理单个单元格值,并测试它们是否包含数字:

Option Explicit

Public x As Double

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim c As Range
    For Each c In Target.Cells
        If c.Interior.ColorIndex = 35 Then
            With Application
                .EnableEvents = False
                If IsNumeric(Target.Value) Then Target.Value = Target.Value + x
                .EnableEvents = True
            End With
        End If
    Next c
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Cells.Count = 1 Then
        If IsNumeric(Target.Value) Then x = Target.Value
    End If
End Sub