Ms access 如何为Access 2010创建VBA循环

Ms access 如何为Access 2010创建VBA循环,ms-access,vba,ms-access-2010,Ms Access,Vba,Ms Access 2010,我想在Form_Load上循环一些VBA代码,这些代码将基于其他两个字段更新表单中的一个字段。目前它只会更新第一条记录,或者当我点击一条记录时 现在看起来是这样的: Private Sub Form_Current() If Style = "W" And Size = "120" Then ContainerType = 9 If Style = "W" And Size = "240" Then ContainerType = 2 If Style = "W" An

我想在Form_Load上循环一些VBA代码,这些代码将基于其他两个字段更新表单中的一个字段。目前它只会更新第一条记录,或者当我点击一条记录时

现在看起来是这样的:

Private Sub Form_Current()

    If Style = "W" And Size = "120" Then ContainerType = 9
    If Style = "W" And Size = "240" Then ContainerType = 2
    If Style = "W" And Size = "360" Then ContainerType = 34
    If Style = "R" And Size = "120" Then ContainerType = 37
    If Style = "R" And Size = "240" Then ContainerType = 5
    If Style = "R" And Size = "360" Then ContainerType = 12
    If Style = "Y" And Size = "120" Then ContainerType = 24
    If Style = "Y" And Size = "240" Then ContainerType = 4
    If Style = "Y" And Size = "360" Then ContainerType = 14
    If Style = ("2Y") And Size = "120" Then ContainerType = 9
    If Style = ("2Y") And Size = "240" Then ContainerType = 25
    If Style = ("2Y") And Size = "360" Then ContainerType = 28
    If Style = ("3Y") And Size = "120" Then ContainerType = 9
    If Style = ("3Y") And Size = "240" Then ContainerType = 51
    If Style = ("3Y") And Size = "360" Then ContainerType = 29

End Sub
也许有更好的方法可以做到这一点?

当然,“更好的方法”是创建一个名为[ContainerType_lookup]的表:

Style  Size  ContainerType
-----  ----  -------------
W      120               9
W      240               2
W      360              34
...
然后使用SQL
JOIN
DLookup()
函数查找相应的
容器类型。那样的话

  • 如果某些内容发生更改(如新的ContainerType),则不必修改代码,并且

  • 如果您需要在应用程序中的任何其他位置派生ContainerType,您也不必在那里复制VBA逻辑


  • 在我看来,我认为您可以使用Select Case将其拆分,使其不那么重。 你也会得到更多的组织,根据你需要的大小或风格对它们进行分组

    但是,我同意使用带或不带查询的表将使您在这里的生活更轻松

    Select Case Size
        Case "120" 
            If Style = "W" Then ContainerType = 9
            If Style = "R" Then ContainerType = 37
            ...
        Case "240"
            If Style = "W" Then ContainerType = 2
            If Style = "R" Then ContainerType = 5
            ...
        Case "360"
            If Style = "W" Then ContainerType = 34
            If Style = "R" Then ContainerType = 12
            ...
        Case Else
            Exit Sub
    End Select
    

    我没有在您的
    ContainerType
    值中看到任何模式。你能解释一下这个代码背后的数学原理吗?