简体   繁体   English

如何获取二维数组中元素的索引?

[英]How to get index of Element in two dimensional array?

I have an array with 2 dimensions.我有一个二维数组。 I also have a For Each loops which loops with elements of these arrays.我还有一个 For Each 循环,它循环使用这些数组的元素。

How can i get a Index of vElement/vElement2 in the moment of my comment here in code?我如何在代码中发表评论时获得 vElement/vElement2 的索引? I would be very, very thankful if You can help me.如果您能帮助我,我将非常非常感谢。

For Each vElement In Table1

    For Each vElement2 In Table2
        If ws_1.Cells(1, c) = vElement Then
            For Row = 3 To lastRow
                    amountValue = amountValue + ws_1.Cells(Row, c).value
                    ws_2.Cells(row2, colIlosc) = amountValue
'Here i would love to have index of vElement for example. In my head it would be something like... Index(vElement) or Index(Table1(vElement))

                    ws_2.Cells(row2, columncodeprod) = vElement2
                    row2 = row2 + 1
                amountValue = 0
            Next Row
        End If
    Next vElement2
Next vElement

There is NO index in the case you put in discussion... vElement and vElement2 variables are of the Variant type.在您讨论的情况下没有索引... vElementvElement2变量属于 Variant 类型。 They are not objects, to have an Index property.它们不是具有Index属性的对象。

When you use a For Each vElement In Table1 loop, VBA starts from the array first element, goes down up to the last row and then do the same for the next column.当您使用For Each vElement In Table1循环时,VBA 从数组的第一个元素开始,向下到最后一行,然后对下一列执行相同操作。

When you need to know what you name arrays 'indexes' you must use For i = 1 To Ubound(Table1, 1) followed by For j = 1 To Ubound(Table1, 2) .当您需要知道数组“索引”的名称时,您必须使用For i = 1 To Ubound(Table1, 1)后跟For j = 1 To Ubound(Table1, 2) In such a case you will know the matching array element row and columns.在这种情况下,您将知道匹配的数组元素行和列。 We can consider them your pseudo-indexes...我们可以将它们视为您的伪索引...

If you really want/insist to extract such indexes in an iteration of type For Each vElement In Table1 , you must build them.如果您真的想要/坚持在For Each vElement In Table1类型的迭代中提取此类索引,则必须构建它们。 I will try en elocvent code example:我将尝试 en elocvent 代码示例:

Sub testElemIndex()
 Dim sh As Worksheet, Table1 As Variant, vElement As Variant
 Dim i As Long, indexRow As Long, indexCol

  Set sh = ActiveSheet

  sh.Range("C6").value = "TestIndex"
  Table1 = sh.Range("A1:E10").value
  For Each vElement In Table1
    i = i + 1:
    If vElement = "TestIndex" Then
        If i <= UBound(Table1, 1) Then
          indexRow = i: indexCol = 1
        Else
          indexCol = Int(i / UBound(Table1, 1)) + 1
          indexRow = i - Int(i / UBound(Table1, 1)) * UBound(Table1, 1)
        End If
        Debug.Print Table1(indexRow, indexCol), indexRow, indexCol: Stop
    End If
  Next
End Sub

You can calculate the rows and columns of the array element.您可以计算数组元素的行和列。 And the code proves that using them, the returned array value is exactly the found one...并且代码证明使用它们,返回的数组值正是找到的值......

Is it a little more light on the array 'indexes'...?是否对数组“索引”有更多了解...?

Show Indices of an element in a 2-dim Array - the complicated way在二维数组中显示元素的索引 - 复杂的方式

If I understand correctly, you are looping through a datafield array via a ► For Each construction and want to get the current row/column index pair of that same array.如果我理解正确,您正在通过 ► For Each构造循环遍历数据字段数组,并希望获取同一数组的当前行/列索引对。

In order to answer your question为了回答你的问题

"How to get indices of an element in a two dimensional array", “如何获取二维数组中元素的索引”,

I leave aside that you would get these automatically in a more evident and usual way if you changed the logic by looping through array rows first and inside this loop eventually through array columns - see Addendum *) .说,如果您通过首先循环遍历数组行并最终通过数组列在此循环中更改逻辑,您将以更明显和更常用的方式自动获得这些 -请参阅附录*)

To allow a reconstruction of eg the 6th array element in the example call below as referring to the current index pair (element i=6 ~> table1(3,2) ~> row:=3/column:=2) it would be necessary为了允许在下面的示例调用中重建例如第 6 个数组元素作为引用当前索引对(元素i=6 ~> table1(3,2) ~> row:=3/column:=2),它将是必要的

  • to add an element counter i by incrementing its value by +1 each time you get the next element and每次获取下一个元素时,通过将其值增加 +1 来添加元素计数器i ,并且
  • to pass this counter as argument (additionally to a reference to the datafield) to a help function getIndex()将此计数器作为参数(以及对数据字段的引用)传递给帮助函数getIndex()

returning results as another array, ie an array consisting only of two values: (1) the current array row, (2) the current array column:将结果作为另一个数组返回,即只包含两个值的数组:(1) 当前数组行,(2) 当前数组列:

Example call示例调用

Note: For better readibility and in order to condense the answer to the mimimum needed (cf MCVE ) the following example call executes only one For Each loop over the table1 datafield array;注意:为了更好的可读性并为了将答案压缩到所需的最小值(参见MCVE ),以下示例调用仅在table1数据字段数组上执行一个For Each循环; you will be in the position to change this to your needs or to ask another question.您可以根据自己的需要更改此设置或提出其他问题。

Option Explicit                         ' declaration head of your code module                     

Sub ShowIndicesOf2DimArray()
    Dim table1                          ' declare variant 1-based 2-dim datafield
    table1 = Sheet1.Range("A2:B4")      ' << change to sheets Code(Name)

    Dim vElem, i As Long
    Dim curRow As Long, curCol As Long  ' current row/column number
    For Each vElem In table1

        i = i + 1                       ' increment element counter
        curRow = getIndex(table1, i)(1) ' <~ get row index via help function 
        curCol = getIndex(table1, i)(2) ' <~ get col index via help function 

        'optional debug info in VB Editors immediate window (here: Direktbereich)
        Debug.Print i & ". " & _
                " Table1(" & curRow & "," & curCol & ") = " & vElem & vbTab;
        Debug.Print ", where curRow|curCol are " & Join(getIndex(table1, i), "|")
    Next vElem
End Sub

Help function getIndex() called by above procedure上述过程调用的帮助函数getIndex()

Function getIndex(table1, ByVal no As Long) As Variant
'Purpose: get 1-based 1-dim array with current row+column indices
    ReDim tmp(1 To 2)
    tmp(1) = (no - 1) Mod UBound(table1) + 1
    tmp(2) = Int((no - 1) / UBound(table1) + 1)
    getIndex = tmp
End Function

在此处输入图片说明

*) Addendum - "the simple way" *)附录 - “简单的方法”

Just the other way round using row and column variables r and c as mentioned above;正好相反,使用如上所述的行和列变量rc allows to refer to an item simply via table1(r,c) :允许通过table1(r,c)简单地引用一个项目:

Sub TheSimpleWay()
    Dim table1                          ' declare variant 1-based 2-dim datafield
    table1 = Sheet1.Range("A2:B4")      ' << change to sheets Code(Name)
    Dim vElem, i As Long
    Dim r As Long, c As Long            ' row and column counter
    For r = 1 To UBound(table1)         ' start by row 1 (1-based!) up to upper boundary in 1st dimension
        For c = 1 To UBound(table1, 2)  ' start by col 1 (1-based!) up to upper boundary in 2nd dimension
            i = i + 1
            Debug.Print i & ". " & _
                " Table1(" & r & "," & c & ") = " & table1(r, c) & vbTab;
            Debug.Print ", where row|col are " & r & "|" & c

        Next c
    Next r
End Sub


Dim Table1() As Variant
Dim Table2() As Variant
Table1 = Range(Cells(2, 3), Cells(lastRow, vMaxCol))
Table2 = Range(Cells(2, 1), Cells(lastRow, 1))

Table1 is Variant(1 to 33, 1 to 9) Table2 is Variant(1 to 33, 1 to 1)表 1 是变体(1 到 33、1 到 9) 表 2 是变体(1 到 33、1 到 1)

This 33 and 9 is dynamic.这个 33 和 9 是动态的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM