VBA中Dictionary对象的Not Like条件判断语句问题
Hey there! Let's figure out why your loop is only picking up the first dictionary entry and fix it.
First, let's recap your current code for clarity:
For Each Key In Players.Keys() If Not (Players(Key).Position Like "*P*") Then 'something' End If Next Key
Common Causes & Fixes
1. You're modifying the dictionary inside the loop
If your 'something' block includes adding, removing, or reassigning entries in the Players dictionary, this will break the enumerator used by the For Each loop. The loop will immediately stop after processing the first entry, making it look like only the first item is being selected.
Fix: Avoid modifying the dictionary during iteration. If you need to make changes, collect the keys you want to modify first in a separate array, then loop through that array to update the dictionary.
2. Case sensitivity is tripping you up
The Like operator in VBScript/VBA is case-sensitive by default. If some entries have a lowercase "p" in their Position instead of uppercase "P", your check will miss them. And if the first entry happens to have no "P"/"p", it'll be the only one caught.
Fix: Normalize the case before checking:
For Each Key In Players.Keys() If Not (UCase(Players(Key).Position) Like "*P*") Then 'your logic here End If Next Key
3. Invalid or null objects in the dictionary
If any entry after the first has a Nothing value (i.e., Players(Key) isn't a valid Player object), accessing its Position property will throw an error. This error stops the loop immediately, so it seems like only the first entry was processed.
Fix: Add a check to ensure the object is valid before accessing its properties:
For Each Key In Players.Keys() If Not Players(Key) Is Nothing Then If Not (UCase(Players(Key).Position) Like "*P*") Then 'your logic here End If End If Next Key
Quick Debugging Step
To narrow down the issue, add a debug line inside the loop to print each entry's details. This will show you exactly what the loop is processing:
For Each Key In Players.Keys() WScript.Echo "Key: " & Key & ", Position: " & Players(Key).Position If Not (Players(Key).Position Like "*P*") Then 'something' End If Next Key
This will help you confirm if the loop is actually stopping early, or if the logic is only matching the first entry.
内容的提问来源于stack exchange,提问作者obizues

