使用数组代码更短

时间:2018-03-13 18:34:32

标签: arrays vba ms-access

我有相同的行重复多次小变化。我想通过使用一个对象数组来缩短它

例如,代替此代码:

Const dCaption = "Me.Lable1.Caption,Me.Lable2.Caption,Me.Lable3.Caption"
Public d(2) As Integer

Public Sub MyMacro()
    Dim vntTemp As Variant
    Dim intIndex As Integer
    vntTemp = Split(lCaption, "d")

    For intIndex = 0 To 2
        db.Execute StartUpdateStr & "Data"& intIndex &  " = " & d(intIndex) & EndUpdateStr & IDAfterSale
    Next
End Sub

我正在寻找类似的东西:

{{1}}

有人能给我正确的语法吗? 谢谢

2 个答案:

答案 0 :(得分:1)

您只需使用Me("Label" & i)

按名称访问标签即可
For intIndex = 0 To 2
    db.Execute StartUpdateStr & "Data" & intIndex &  " = " _
        & Me("Label" & (intIndex + 1)).Caption _
        & EndUpdateStr & IDAfterSale
Next

答案 1 :(得分:0)

我想你将来会添加很多标签。那么你可以使用下面的代码

Private Sub PrintAllLabel()
     For Each ctl In Me.Controls
         If TypeName(ctl) = "Label" Then
              db.Execute StartUpdateStr & "Data" & intIndex &  " = " _
              & ctl.Caption _
              & EndUpdateStr & IDAfterSale
         End If
     Next ctl
 End Sub