0

这个 VBA 问题也可能适用于 Microsoft Office,尽管我在 object中遇到过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)
4

1 回答 1

1

Dictionary.Items()是一个返回[*]的方法。仅当迭代变量也是 a时,您Array of Variant才能迭代,或者您可以使用结构。For Each ...VariantFor ... 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()

于 2016-09-29T12:16:21.743 回答