语言:VBA-MS Access
我在代码中使用了用户定义类型(UDT)。 我希望能够根据状态变量确定将数据加载到UDT的哪个部分。我的第一个尝试是使用嵌套在“ IF”语句中的“ With”语句。这是行不通的(我收到一个编译错误,提示“ Else if 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
答案 0 :(得分:1)
您不能以这种方式使用With
。编译器不允许这种有条件的嵌套代码。不使用With
,不使用For
,不使用其他任何东西。
但是,您可以使用变量来确定要在其中使用的值:
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