【问题标题】:VBA - Nested "With Statements" within "IF Statements"VBA - 在“IF 语句”中嵌套“With 语句”
【发布时间】:2018-12-06 14:55:53
【问题描述】:

语言: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

【问题讨论】:

  • 你应该展示你的研究,包括你的错误。
  • @jdv 我不明白那个评论。 我得到一个编译器错误,说 Else without if 是一种可接受的方式来描述错误 imo。我唯一想念的是导致错误的行,但编译错误并不总是存在。我认为这个问题问得很好。
  • 显示,不告诉。见How to Ask。我们有理由想看看您尝试了什么,以及您得到了什么结果。你真的认为描述错误信息的句子片段足够清晰吗?因为不是。

标签: ms-access if-statement vba with-statement user-defined-types


【解决方案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

【讨论】:

    猜你喜欢
    • 2016-04-23
    • 2017-03-06
    • 2021-01-15
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    相关资源
    最近更新 更多