语言:VBA - MS Access
我在代码中使用用户定义类型 (UDT)。
我希望能够根据状态变量确定我正在将数据加载到 UDT 的哪个部分。我的第一次尝试是使用嵌套在“IF”语句中的“With”语句。这不起作用(我收到一个编译器错误,显示 Else without if)。有办法让这项工作发挥作用吗?或者使用状态变量来确定我正在加载 UDT 的哪个部分的另一种方法?
Type MyOtherType
Name as String
Age as Integer
End Type
Type MyType
aMyOtherType() as MyOtherType
X as Integer
Y as Integer
Z as Integer
End Type
Sub QuestionableCode()
Dim UDT(0 To 0) as MyType
Dim State as String
ReDim Preserve UDT(0).X(0 to 0) as MyOtherType
ReDim Preserve UDT(0).Y(0 to 0) as MyOtherType
ReDim Preserve UDT(0).Z(0 to 0) as MyOtherType
State = "B"
If State = "A" Then
With UDT(0).X(0)
ElseIf State = "B" Then
With UDT(0).Y(0)
Else
With UDT(0).Z(0)
End If
.Name = "George"
.Age = 30
End With
End Sub
你不能与With
那样。编译器不允许这种有条件嵌套的代码。不与With
,不与For
,不与其他任何东西一起。
但是,您可以使用变量来确定要在 with 中使用哪个值:
Sub QuestionableCode()
Dim UDT(0 To 0) as MyType
Dim State as String
ReDim Preserve UDT(0).X(0 to 0) as MyOtherType
ReDim Preserve UDT(0).Y(0 to 0) as MyOtherType
ReDim Preserve UDT(0).Z(0 to 0) as MyOtherType
State = "B"
Dim myWithVariable
If State = "A" Then
myWithVariable = UDT(0).X(0)
ElseIf State = "B" Then
myWithVariable = UDT(0).Y(0)
Else
myWithVariable = UDT(0).Z(0)
End If
With myWithVariable
.Name = "George"
.Age = 30
End With
End Sub
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)