Arrays 在多维数组中查找值

Arrays 在多维数组中查找值,arrays,excel,vba,Arrays,Excel,Vba,myArray正在存储在调用子过程之前需要检查的数据。它有3列: Col1:字符串 Col2:时间戳 Col3:字符串 我需要检查: 如果第1列中存在Function参数给定的字符串 如果是,那么从现在到第2列中对应字符串的最新时间戳的时间差是多少 For n = 1 To UBound(myArray, 2) If myArray(1, n) = myString Then myTimeStamp = myArray(2, n) 'find the timestam

myArray正在存储在调用子过程之前需要检查的数据。它有3列:

  • Col1:字符串
  • Col2:时间戳
  • Col3:字符串
我需要检查:

  • 如果第1列中存在Function参数给定的字符串
  • 如果是,那么从现在到第2列中对应字符串的最新时间戳的时间差是多少

    For n = 1 To UBound(myArray, 2)
        If myArray(1, n) = myString Then
            myTimeStamp = myArray(2, n) 'find the timestamp of this string in col2
            myTimeDiff = DateDiff("n", myTimeStamp, DateTime.Now()) ' calculate the time difference in minutes
            myIndex = n 'return the array index (n)
        End If
    Next n
    
    因为数组是按顺序填充时间戳的,所以我知道col1中给定字符串的最新值也是最新值


  • 但是myIndex返回的是空字符串,为什么?

    VBA中的数组通常以LBound=0开头,因此for循环应该是:

    For n = 0 to UBound(myArray)
    
    试试这个

    For n = 1 To UBound(myArray, 1)
        If myArray(n, 1) = myString Then
            myTimeStamp = myArray(n, 2) 'find the timestamp of this string in col2
            myTimeDiff = DateDiff("n", myTimeStamp, DateTime.Now()) ' calculate the time difference in minutes
            myIndex = n 'return the array index (n)
        End If
    Next n
    

    您是否尝试过在调试模式下单步执行代码?这会给你答案。另外,为什么
    myIndex
    是一个字符串???@Jean-FrançoisCorbett在调试模式下没有错误。myIndex应该是一个整数,它只是返回一个空字符串。您的代码是否输入了IF条件?@SiddharthRout是的,它输入了。好的,高亮显示行
    myIndex=n
    ,然后逐步检查它,然后检查
    n/myIndex
    的值。我已经设置了“Option Base 1”,那么这不是问题。。。你申报我的索引了吗?如果不是,它只存在于循环内部,并且在循环外部具有null值。。。一旦找到字符串,就可以退出循环。那么n是您需要的索引;)