VBA - Nested “With Statements” within “IF Statements”

[亡魂溺海] 提交于 2021-01-04 07:35:07

问题


Language: VBA - MS Access

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

回答1:


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


来源:https://stackoverflow.com/questions/51067401/vba-nested-with-statements-within-if-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!