如何在没有重复代码的情况下编写 or 语句 (VBA)

  • 本文关键字:or 语句 VBA 情况下 代码 vba
  • 更新时间 :
  • 英文 :


我知道在大多数其他语言中,你可以编写一个表达式if (ptr == NULL || ptr->foo()) {something bad happened}来测试变量的有效性和你想要执行的测试。 VBA不允许您这样做。 所以我正在绞尽脑汁想办法编写以下代码,而无需 1( 使用错误捕获作为条件分支的手段和 2( 不重复代码。

Type Vector
vData() as Variant
vSize as Long
End Type
Sub add(v as Vector, elem as Variant)
Dim oldSize as Long
if v.vSize = 0 Or UBound(v.vData) >= v.vSize then
oldSize = v.vSize
ReDim Preserve v.vData(0 to (oldSize * 2 + 1))
v.vData(oldSize) = elem
v.vSize = v.vSize + 1
else
v.vData(v.vSize) = elem
v.vSize = v.vSize + 1
end if
End Sub

现在,无论 vSize 是否为 0(如果 vData 从未变暗(,代码都将在 UBound 行上崩溃。 我能看到的唯一另一种方法是做一个额外的 elseif 语句来检查 UBound,但这会复制将向量大小加倍的代码。

如果您认为这是重复的: VBA 短路"和"替代方案 . 这讨论了 AND 语句(不是 or(的替代方案。 嵌套的 ifs(又名 AND 语句(不会像 OR 那样复制代码。

如果我理解正确,您需要检查数组是否已分配。

一个这样的选择是这样做(无论它看起来多么奇怪(:

If (Not Not MyArray) <> 0 Then 'Means it is allocated

答案取自此线程 - 请参阅以获取更多想法。

使用SnowGroomer的答案,我发布了完整的解决方案:

这是一个名为 Vector 的类

Private data() As Variant
Private size As Long
Property Get vSize() As Long
vSize = size
End Property
Property Let vData(ByVal index As Long, elem As Variant)
If index < 0 Then Exit Property
If index < size Then
data(index) = elem
Else
Me.add elem, index
End If
End Property
Property Get vData(ByVal index As Long) As Variant
If index < 0 Or (Not Not data) = 0 Then
vData = Nothing
Exit Property
End If
vData = data(index)
End Property
Public Sub add(elem As Variant, Optional index As Long = -1)
If index > -2 Then
If index = -1 Then
If size = 0 Or (Not Not data) = 0 Then
ReDim data(0)
data(size) = elem
size = size + 1
Exit Sub
Else 'size <> 0
ReDim Preserve data(0 To size * 2 + 1)
data(size) = elem
size = size + 1
End If
Else 'index <> -1
If index >= size Then
ReDim Preserve data(0 To index)
data(index) = elem
size = index + 1
Else 'index < vSize
data(index) = elem
End If 'index >= vSize
End If 'index = -1
End If 'index > -2
End Sub 'add

最新更新