为什么我在这段VBA代码中只得到案例1的结果?[已关闭]

问题描述 投票:0回答:1

当我运行我的代码时,我得到5个 "喵 "MsgBoxes,而不是 "喵 "和 "汪"。

Dim animal As Range
Set animal = shB.Range("M3:M8")

For Each Cell In animal

    Select Case Cell
        Case Is = cat
            MsgBox "meow"
        Case Is = dog
            MsgBox "woof"
    End Select

Next Cell
End Sub
excel vba excel-vba loops case
1个回答
0
投票

正如评论中所建议的那样。Option Explicit 将帮助你准确地写出你的代码,并允许你快速地识别间隙错误。你应该声明所有的变量,然后在你的代码中适当地分配你的变量。

在您的示例中,您有 例如声明什么是shB。

对于Select Case语句,你可以使用 Case Is虽说我 不要 认为可以使用 Case Is =

试试这个,我测试了一下,它对我有效----------。

Option Explicit

Sub SelectCase_Example()
 Dim wshB As Worksheet
 Dim rAnimal As Range
 Dim rCell As Range

    Set wshB = ActiveSheet
    Set rAnimal = wshB.Range("M3:M8")

    For Each rCell In rAnimal
        Select Case rCell
            Case "cat"
                MsgBox "Meow!"
            Case "dog"
                MsgBox "woof!"
        End Select
    Next rCell
End Sub

0
投票
Option Explicit

Sub Sounds()

  Dim animal As Range
  Dim cell   As Range

  Set animal = ActiveSheet.Range("M3:M8")

  For Each cell In animal

    Select Case cell
        Case Is = "cat"
            MsgBox "meow"
        Case Is = "dog"
            MsgBox "woof"
    End Select

  Next cell

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.