根据其他相关数组确定一个数组的元素位置

问题描述 投票:0回答:1

我有3个数组动态数组(大小在运行时确定):

dim arrName() as String 
dim arrQty() as Integer
dim arrDate() as Date

这些数组是相互关联的:例如,

**第一个数组:我有3个过程分别命名为Procedure1,Procedure2,Procedure3-arrName(Procedure1,Procedure2等,大小为3。

[第二数组:分别指定的每个过程的数量-arrQty(Qty1,Qty2等),大小分别为3。Qty2-表示Procedure2被指定的Qty2倍...

第三数组:按顺序规定的过程的日期,例如,如果arrQty(1)= 2,则意味着arrDate()的前2个元素将是Procedure1的2个日期。数组的大小将是arrQty()的元素之和。例如,如果arrQty()= [2,2,4],则arrDate()的大小为8。*

问题是;知道arrDate()元素的位置,如何解析确定其名称?

例如arrDate(4)与arrName(2)相关,arrDate(7)与arrName(3)相关,等等...

P.S。我可以创建第四个数组,其大小为arrDate(),并分别用arrName()的元素填充它,例如[Procedure1,Procedure1,Procedure2等],但是还有更聪明的方法吗?

arrays vba math relation
1个回答
0
投票

首先,像默认值一样,VBA使用基于零的数组。这意味着数组元素之间的迭代从零开始。除非您确实使用Option Base 1或像它们一样明确声明Dim arrName(1 To 3)。下一段代码将向您展示如何匹配问题中的示例数组。我假设一对(arrDate的两个日期)都属于较短数组的元素。如果没有,您只能选择符合您需求的线。代码在不同的行上返回它们两者:

Sub testArraysMatching()
 Dim arrName() As String
 Dim arrQty(2) As Integer
 Dim arrDate(5) As Date
 Dim i As Long

 arrName() = Split("Procedure1,Procedure2,Procedure3", ",")
 arrQty(0) = 3: arrQty(1) = 6: arrQty(2) = 10
 arrDate(0) = Date: arrDate(1) = Date + 1: arrDate(2) = Date + 2: arrDate(2) = Date + 3
 arrDate(3) = Date + 4: arrDate(4) = Date + 5: arrDate(5) = Date + 6
  Debug.Print LBound(arrName), UBound(arrName) 'it will return 0 and 2
 For i = LBound(arrName) To UBound(arrName)
    'return the corresponding quantity:
    Debug.Print "Quantity for " & arrName(i) & " is " & arrQty(i)
    'return the coresponding (both) dates:
    Debug.Print "Date 1 for " & arrName(i) & " is " & arrDate(i * 2)
    Debug.Print "Date 2 for " & arrName(i) & " is " & arrDate(i * 2 + 1)
 Next i

 'find name for a Date element:
 Dim testDate As Date, boolFound As Boolean
   testDate = Date + 10
   For i = LBound(arrDate) To UBound(arrDate)
        If arrDate(i) = testDate Then
            Debug.Print arrName(Int(i / 2)): boolFound = True
        End If
   Next i
   If Not boolFound Then MsgBox "The date """ & testDate & """ not found in ""arrDate""."
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.