VBA 循环遍历集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36270212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA Looping through a Collection
提问by GhostTiger
I have a collection of files that I selected in the SelectManyFiles function and I want to run multiple private subs on each Drawing in the collection function. Here's my code:
我有一个在 SelectManyFiles 函数中选择的文件集合,我想在集合函数中的每个绘图上运行多个私有子文件。这是我的代码:
Sub Main()
Dim Drawing As Object
Dim Drawings As Collection
Set Drawings = SelectManyFiles()
For Each Drawing In Drawings
'Call multiple private subs to run on each drawing
Next Drawing
End Sub
I think there's something wrong with the loop but not sure exactly! Any help is appreciated.
我认为循环有问题,但不确定!任何帮助表示赞赏。
回答by Dick Kusleika
The collection that's returned by SelectManyFiles is not returning a collection of objects. It's probably returning a collection of Strings, but that's just a guess. Change your sub to this
SelectManyFiles 返回的集合未返回对象集合。它可能会返回一个字符串集合,但这只是一个猜测。将您的子更改为此
Sub Main()
Dim Drawing As Variant
Dim Drawings As Collection
Set Drawings = SelectManyFiles()
For Each Drawing In Drawings
Debug.Print TypeName(Drawing)
Next Drawing
End Sub
And see what the Debug.Print gives you. If it's any scalar (string, long, double, Boolean, etc), then you need to declare Drawingas Variant. Only if all of the collection items are objects can you use Object.
看看 Debug.Print 给你什么。如果是任何标量(字符串、长整型、双精度、布尔型等),则需要声明Drawing为 Variant。只有当所有集合项都是对象时,才能使用 Object.

