首页 > 解决方案 > 如何找到数组的维数?

问题描述

下面是一段代码,我需要通过传递的消息来存储有关警告消息的一些信息。传递的参数本身是一个变体,由 API 调用设置SAPListOfMessages,返回一个数组String。然而,我注意到的是,只要有超过 1 个警告,列表就是 2D 并且messageList(x-1)显然会导致错误,因为它不是正确的索引。同样奇怪的是for each循环似乎忽略了维度,并以某种方式将数组展平并循环遍历它,就好像它是一维的一样。我看到的唯一解决方法是在做任何其他事情之前检查数组有多少维,因此我的问题。我找不到任何关于获取维度数量的信息——我只找到了关于它们的界限的信息。是否可以在 VBA 中找到数组的维数?如果没有,你会建议我如何解决这个问题?

Sub getOverlapWarnings(ByRef messageList As Variant, ByRef warnings As Dictionary)

  Dim msg As Variant
  Dim x As Integer
  x = 1
 'look for an overlap warning message in the list of messages
  For Each msg In messageList
    'look for the keyword 'overlap' in the list of messages
    
    If InStr(1, msg, "overlap") <> 0 Then
       warnings.Add messageList(x - 1), msg
    End If
   x = x + 1
  Next msg
End Sub

标签: vbaexcel

解决方案


是否可以在 VBA 中找到数组的维数?

这种方法增加了可能的维度计数,60 是内置的最大值(cf 注释):

Private Function nDim(ByVal vArray As Variant) As Long
' Purpose: get array dimension (MS)
Dim dimnum     As Long
Dim ErrorCheck As Long    ' OP: As Variant
On Error GoTo FinalDimension

For dimnum = 1 To 60        ' 60 being the absolute dimensions limitation 
    ErrorCheck = LBound(vArray, dimnum)
Next
' It's good use to formally exit a procedure before error handling
' (though theoretically this wouldn't needed in this special case - see comment) 
Exit Function

FinalDimension:
nDim = dimnum - 1

End Function

更多链接(谢谢@ChrisNeilson)

MS 使用数组

大阵列


推荐阅读