VBA - 在“IF语句”中嵌套“带语句”

问题描述 投票:1回答:1

语言:VBA - MS Access

我在我的代码中使用用户定义类型(UDT)。我希望能够根据状态变量确定UDT的哪个部分正在加载数据。我的第一次尝试是使用嵌套在“IF”语句中的“With”语句。这不起作用(我得到一个编译器错误,如果没有,则说明Else)。有没有办法让这项工作?或者另一种方法是使用状态变量来确定我正在加载的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
if-statement access-vba with-statement user-defined-types
1个回答
1
投票

你无法以这种方式使用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
© www.soinside.com 2019 - 2024. All rights reserved.