Excel VBA 代码抛出 运行-time error '13': 类型不匹配错误

Excel VBA code throwing Run-time error '13': Type mismatch error

我无法弄清楚 Excel 中 VBA 代码的第二行(下面的要点)导致了“运行 时间错误'13':类型不匹配。”在 $B$1 中,我创建了一个下拉列表,并根据选择的值调用相应的宏 运行 (这些都是隐藏某些列以管理自定义视图的宏)。该代码正在运行,但不断抛出我必须清除的错误。我研究并尝试将 Target.Value 更改为 Target.Text,但这没有帮助?

Private Sub Worksheet_Change(ByVal Target As Range)

If (Target.Address = "$B") And (Target.Value = "Default View") Then 
    Call Default_View
ElseIf (Target.Address = "$B") And (Target.Value = "Compact View") Then
    Call Compact_View
ElseIf (Target.Address = "$B") And (Target.Value = "Search View") Then
    Call Search_View
ElseIf (Target.Address = "$B") And (Target.Value = "Sessions Only") Then
    Call Sessions_Only
ElseIf (Target.Address = "$B") And (Target.Value = "Session Trends") Then
    Call Session_Trends
ElseIf (Target.Address = "$B") And (Target.Value = "Jump to Direct") Then
    Range("HN358").Select
Else: Call Show_All

End If

End Sub

我建议您将逻辑分开,首先询问地址是否为 $B$1,然后在该位置检查 target.value。如果您知道地址是您的控件,则仅查询该值。

如果用户更改了 >1 个单元格,则您无法将 Target.Value 与字符串进行比较。 也许尝试更像这样的东西:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "$B" Then             'no need to repeat this test
        Select Case Target.Value
            Case "Default View": Default_View   'use of Call is deprecated
            Case "Compact View": Compact_View
            '...other cases
            Case Else: Show_All
        End Select
    End If
End Sub