指导,VBA - 选择案例清理

时间:2017-06-19 14:40:19

标签: vba access-vba

SELECT CASE方案对我有用,但我认为代码可以更友好......任何建议都会非常有用。

Select Case True 'select case where worker name and action is true then in each case RSworkhours.addnew

    Case Me.Worker1.Value <> "" And Me.fw1a1 = 1
        With RsWorkHours
            .AddNew
            !WorkerID = Me.Worker1
            !Date = Me.TxtDate
            !StandardTime = Me.w1a1s
            !Overtime = Me.w1a1o
            !Doubletime = Me.w1a1d
            !ScaffoldID = Me.cboScaffnum
            .Update
        End With
        Me.fw1a1 = 0
        GoTo WorkerHours
   Case Me.Worker1.Value <> "" And Me.fw1a2 = 1
        With RsWorkHours
            .AddNew
            !WorkerID = Me.Worker1
            !Date = Me.TxtDate
            !StandardTime = Me.w1a2s
            !Overtime = Me.w1a2o
            !Doubletime = Me.w1a2d
            !ScaffoldID = Me.cboScaffnum
            .Update
        End With
        Me.fw1a2 = 0
        GoTo WorkerHours

如果有16名工人,并且每人有5个动作,则代码将遍历此Select Case 80次。

我在考虑可能有一个循环来修改参数中的数字,如:

for each x to 16
    for each y to 5
        If Me.worker & x & .Value <> "" And Me.fw & x & a & y Then
            With Recordset
                .AddNew
                'insert stuff
                .Update
            End With
        End If
    Next y
Next x

有没有人有任何见解? 提前谢谢。

-Matt ATTACHED IS AN IMAGE OF THE FORM JUST TO GET AN UNDERSTANDING OF WHAT THE CODE IS DOING.

1 个答案:

答案 0 :(得分:2)

您可以通过Controls collection的名称访问所有控件。

只需传递一个控件的名称即可进入该控件 - 名称是一个字符串,当然可以是动态的。

Dim x As Long, y As Long
Dim WorkerX As Control, wXaYs As Control, wXaYo As Control, wXaYd As Control

For x = 1 To 16
    For y = 1 To 5
        Set WorkerX = Me.Controls("Worker" & x)
        Set wXaYs = Me.Controls("w" & x & "a" & y & "s")
        Set wXaYo = Me.Controls("w" & x & "a" & y & "o")
        Set wXaYd = Me.Controls("w" & x & "a" & y & "d")
        If WorkerX.Value > "" And wXaYs.Value > "" Then
            With Recordset
                .AddNew
                !WorkerID = WorkerX.Value
                !Date = Me.TxtDate
                !StandardTime = wXaYs.Value
                !Overtime = wXaYo.Value
                !Doubletime = wXaYd.Value
                !ScaffoldID = Me.cboScaffnum
                .Update
            End With
        End If
    Next y
Next x