当我运行我的代码时,我得到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
正如评论中所建议的那样。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
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