在excel 2003中基于单元格值运行不同的宏不起作用

时间:2018-03-17 06:04:03

标签: excel-vba vba excel

我正在运行excel 2003并尝试根据单元格值(当前工作表中的所有内容)调用几个不同的宏。我的宏不起作用,我无法理解为什么 - 这是宏:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("C9")) Is Nothing Then
        Select Case Range("C9")
            Case "Select":  HideST
            Case "YES":     HideST
            Case "NO":      FindST
        End Select
     End If
 End Sub

我也试过这个:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim sourceSheet As Worksheet
    Set sourceSheet = ActiveSheet
    If Not Intersect(Target, Range("C9")) Is Nothing Then
        Select Case ActiveSheet.Range("C9")
            Case "Select": HideST
            Case "YES":    HideST
            Case "NO":     FindST
        End Select
    End If
End Sub

但是,它也不起作用...... 然后我尝试了完全不同的宏 - 结果相同:

Sub Worksheet_Change(ByVal Target As Range)
    Set Target = Range("C9")
    If Target.Value = "YES" Then
        Call HideST
    End If
    If Target.Value = "NO" Then
        Call FindST
    End If
End Sub

当我在C9上选择不同的值时 - 由于未触发宏,所以没有任何反应。有人可以帮忙吗?

干杯 Mile`S

2 个答案:

答案 0 :(得分:2)

选项1 (就像保罗在评论中所说)

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("C9")) Is Nothing Then
        Select Case Ucase(Range("C9").value2)
            Case "SELECT", "YES":  HideST
            Case "NO":             FindST
        End Select
     End If
 End Sub

选项2

Option Explicit
Option Compare Text
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("C9")) Is Nothing Then
        Select Case Range("C9").value2
        Case "Select", "YES" : HideST
        Case "NO":             FindST
        End Select
    End If
End Sub

对于Option Compare,请查看MSDN

上的文档

答案 1 :(得分:1)

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    With Target

        If .Column = 3 And .Row = 9 Then

            Select Case UCase(.Value2)

                Case "SELECT", "YES":   HideST
                Case "NO":              FindST

            End Select

        End If
    End With
 End Sub

确保将代码放在模块中以获取正确的工作表(单元格C9所在的位置)

VBE sample