vba - 如何找到数组的维数?
问题描述
下面是一段代码,我需要通过传递的消息来存储有关警告消息的一些信息。传递的参数本身是一个变体,由 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
解决方案
是否可以在 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)
推荐阅读
- sql - 在 Oracle Apex 中单击按钮时显示 APEX$ROW_ACTION
- apache-kafka - Kafka - 当前 ISR Set(1) 的大小不足以满足分区 __consumer_offsets-0 的 min.isr 要求 2
- angular - Angular 11 - 订阅不返回响应类型文本的正确数据
- javascript - React hook,更新后直接访问状态值
- python - 如何使用 Tkinter 将多个 Dataframes 导出到多个 Excel 工作表?
- swift - 使用 URLSession.shared.dataTask Data Swift 解密 CommonCrypto 总是返回 nil
- c# - 不执行方法释放锁
- javascript - 如何在 nodeJS API 中自动化我的发布请求?
- tclsh - tclsh 相当于 bash 的 -c(运行命令)是什么?
- javascript - 如何使用 javascript vanilla 将数组与另一个元素进行比较