此VBA问题也可能适用于Microsoft Office,尽管我使用autodesk-inventor对象Inventor.Sheet
来体验它。所以,请不要犹豫,回答VBA + Office的经验。
初始化Inventor.Sheet
可用作:
Debug.Print oSheet.TitleBlock.Name ' prints "Title Block 1"
以及
Debug.Print oSheet ' prints 11234869 long integer, value of default member
这种二元行为是由对象的默认属性引起的。
问题在于每当我使用
时Dim TitleBlocksLargestSheet As Scripting.Dictionary
TitleBlocksLargestSheet.Add oTitleBlock, oSheet
然后添加到字典中插入长整数值而不是oSheet
的对象引用。
如何将对象引用插入字典?
我怀疑在Add
操作之前,字典=
方法更喜欢Set
操作。
因此,在以下示例中,我总是在字典项而不是对象中使用整数:
'*** get a dictionary of used title blocks (corner stamps) with largest sheet size for each
For Each oSheet In oDrawingDocument.Sheets
'** get title block of active sheet
Dim oTitleBlock As Inventor.TitleBlock
Set oTitleBlock = oSheet.TitleBlock
If Not oTitleBlock Is Nothing Then
'** add or update title block usage
If Not TitleBlocksLargestSheet.Exists(oTitleBlock) Then
TitleBlocksLargestSheet.Add oTitleBlock, cobj(oSheet)
Else
Dim oLargestSheetSeen As Inventor.Sheet
Set oLargestSheetSeen = TitleBlocksLargestSheet(oTitleBlock)
If oSheet.Width * oSheet.Height > oLargestSheetSeen.Width * oLargestSheetSeen.Height Then
TitleBlocksLargestSheet.Item(oTitleBlock) = oSheet
End If
End If
End If
Next oSheet
-- *** usage - retrieval from the dictionary
For Each oSheet In TitleBlocksLargestSheet.Items 'ERROR 424: Object required.
Set oTitleBlock = oSheet.TitleBlock
'...some other code
Next oSheet
更新:
Debug.Print TypeName(TitleBlocksLargestSheet.Item(oTitleBlock))
IRxSheet ' perhaps there's no problem with storage but with retrieval?
Debug.Print VarType(TitleBlocksLargestSheet.Item(oTitleBlock))
3 ' (Long Integer)
答案 0 :(得分:1)
Dictionary.Items()
是method返回Array of Variant
[*]。仅当迭代变量也是For Each ...
时,您才能使用Variant
进行迭代,或者您可以使用For ... To ...
结构。
Dim oSheet as Inventor.Sheet
Dim vSheet as Variant
Dim iSheet as long
'Use this way
For Each vSheet In TitleBlocksLargestSheet.Items
Set oSheet = vSheet ' you may want to check that vSheet is really a Sheet before
Set oTitleBlock = oSheet.TitleBlock
'...some other code
Next vSheet
'or this one
For iSheet = 0 to TitleBlocksLargestSheet.Count - 1
Set oSheet = TitleBlocksLargestSheet.Item(iSheet)
Set oTitleBlock = oSheet.TitleBlock
'...some other code
Next iSheet
[*]您可以使用打印Debug.Print TypeName(TitleBlocksLargestSheet.Items)
Variant()
进行检查