VBA-嵌套的“带有语句"在"IF语句"中 [英] VBA - Nested "With Statements" within "IF Statements"
问题描述
语言:VBA-MS Access
Language: VBA - MS Access
我在代码中使用了用户定义类型(UDT).我希望能够根据状态变量确定将数据加载到UDT的哪个部分.我的第一个尝试是使用嵌套在"IF"语句中的"With"语句.这是行不通的(我收到一个编译错误,提示"Else if if").有没有办法使这项工作?还是使用状态变量来确定我正在加载UDT的哪一部分的另一种方式?
I am using User-Defined-Types (UDT) within my code. I would like to be able determine which section of the UDT i'm loading data into based on a state variable. My first attempt was to use "With" statements nested into an "IF" statement. This doesn't work (I get a compiler error that says Else without if). Is there a way to make this work? or another way of going about using a state variable to determine which section of the UDT i'm loading?
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
.编译器不允许这种有条件的嵌套代码.不使用使用
,不使用 For
,不使用其他任何东西.
You can't work with With
that way. The compiler doesn't allow this kind of conditionally nested code. Not with With
, not with For
, not with anything else.
但是,您可以使用变量来确定要在其中使用的值:
You can, however, use a variable to determine which value you're going to use in your 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
这篇关于VBA-嵌套的“带有语句"在"IF语句"中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!