2016-08-19 1 views
0

私は質問を説明するためにいくつかのコードを書くつもりです。For Each oItem LoopのVBAでは、どのようにoItemのIDにアクセスできますか?

For Each oElement in myArray 
    MsgBox oElement 
Next 

これは「MyArrayという」の要素があるとして「oElement」の値が何倍として「MyArrayという」に含まれているというメッセージを印刷します。

しかし、 "oElement"のIDを知りたいのですが?私がアクセスできる "oElement"のプロパティはありますか? oelementの値の代わりにoelementの数を表示するような何か?

For Each oElement in myArray 
    MsgBox oElement.ID 
Next 

可能ですか?アクセスできるプロパティはありますか?あなたの時間と注意を事前に

おかげで、

+0

バリアントが配列またはコレクションの場合にのみ、それぞれに対して実行できます。その純粋な配列の場合、何にもアクセスするためのプロパティはありません。索引に興味がある場合は、 'lbound'から' ubound'にループしてください。そのコレクションの場合、基礎となるオブジェクトが公開するすべてのプロパティにアクセスできます。完全に合意された – cyboashu

答えて

1

いいえ、配列内のアイテムのインデックスを取得する方法はありません。あなたは、別の変数を維持する必要があります。

Dim Index As Integer 

Index = 0 
For Each oElement In myArray 
    Print Index 
    Index = Index + 1 
Next 
+0

。髪を分割するのではなく、この方法で 'option base'の設定も考慮する必要があります。 – cyboashu

+0

私はそれをどのように解決したのですか?しかし、ちょうど私がアクセスできるクリーンなプロパティがないことを確認したいと思っていました。ありがとうございました。 – RaRdEvA

0

回避策は代わりにVariant配列のDictionaryオブジェクトの使用が考えられます。

「test」を返すために、次の機能を使用しています
Sub main() 
    Dim myDict As Scripting.Dictionary 
    Dim key As Variant 

    Set myDict = GetDict '<--| get your "test" dictionary with "indexes" as 'keys' and "elements" as 'items' 

    For Each key In myDict.Keys '<--| iterate over keys (i.e. over your "indexes") 
     MsgBox key '<--| this will give you the "index" 
     MsgBox myDict(key) '<--| this will give you the "element" 
    Next key 
End Sub 

辞書真実で

Function GetDict() As Scripting.Dictionary 
    'function to return a test dictionary 

    Dim i As Long 
    Dim myDict As New Scripting.Dictionary 

    For i = 1 To 10 
     myDict.Add i, "string-" & CStr(i) '<--| use the 'key' as your "index" and the 'item' as your element 
    Next i 
    Set GetDict = myDict 
End Function 

、以下アプローチは、より多くのsimilaに見える可能性がありRあなたの最初のコードに以下の機能を使用している

Sub main() 
    Dim myDict As Scripting.Dictionary 
    Dim oElement As Variant 

    Set myDict = GetDict2 '<--| get your "test" dictionary with "elements" as 'keys' and "indexes" as 'items' 

    For Each oElement In myDict.Keys '<--| iterate over dictionary keys (i.e. over your "elements") 
     MsgBox myDict(oElement) '<--| this will give you the "index" 
     MsgBox oElement '<--| this will give you the "element" 
    Next oElement 
End Sub 

Function GetDict2() As Scripting.Dictionary 
    Dim i As Long 
    Dim myDict As New Scripting.Dictionary 

    For i = 1 To 10 
     myDict.Add "string-" & CStr(i), i '<--| use the 'key' as your "element" and the 'item' as your key 
    Next i 
    Set GetDict2 = myDict 
End Function 

が、それはこのように、おそらく彼らの一意に違反し、keysとしてあなたの「要素」を使用しての主な欠点を持っていると思います、連続した整数は常にこの要件を満たします。

+0

私はこのアプローチがまさに私の心が探していたものであることに同意します。欠点は、一意性と片面性(簡単にするため)のために、時間とコード行を節約するためにマニュアルカウンターを追加する方が簡単です(前の回答のように)。 – RaRdEvA

関連する問題