0

I have the same line Repeating many times with small changes. i like to shorten it by using an array of objects

For example, instead of this code:

StartUpdateStr = "Update tblAfterSale SET "
EndUpdateStr = " WHERE IDAfterSale = "
IDAfterSale = Me.lblIDAfterSale.Caption

db.Execute StartUpdateStr & "Data1 = " & Me.Lable1.Caption & EndUpdateStr & IDAfterSale
db.Execute StartUpdateStr & "Data2 = " & Me.Lable2.Caption & EndUpdateStr & IDAfterSale
db.Execute StartUpdateStr & "Data3 = " & Me.Lable3.Caption & EndUpdateStr & IDAfterSale
db.Close

I'm looking for something like this:

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

Can someone write me the right syntax? Thank you

1
  • You can update multiple columns in a single query: update T set a=1, b=2, c=3 where ... so there is no need for 3 trips to the database. You should be using a parameterized insert to avoid injection vulnerabilities. Commented Mar 13, 2018 at 18:42

2 Answers 2

1

You can simply access the labels by name with Me("Label" & i)

For intIndex = 0 To 2
    db.Execute StartUpdateStr & "Data" & intIndex &  " = " _
        & Me("Label" & (intIndex + 1)).Caption _
        & EndUpdateStr & IDAfterSale
Next
Sign up to request clarification or add additional context in comments.

Comments

0

I suppose you will be adding many labels in future. So can you use the below code

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

1 Comment

thank you all. all 3 comments help me :) my code is much nicer now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.