0

I have a userform in VBA that has some pictures. I need to loop through 15 pictures that have names like:

imm1, imm2, ...,imm15

And I create the paths for the pictures:

dir1 = "c:\..\pi1.jpg"
...
dir15 = "c:\..\pi15.jpg"

I'd like to create a loop like:

    For i = 1 To 15
    (imm & i).Visible = True
   (imm & i).Picture = LoadPicture(dir & i)
    Next i

What is the correct way to do it?

1
  • Please use FSO to combine paths and filenames instead of &. More details here Commented Jul 16, 2014 at 14:02

2 Answers 2

1

You can reference each image using it's name in the Controls property of the userform like so:

Public Sub VisibleImages()

Dim i As Integer

For i = 1 To 15
    Me.Controls("imm" & i).Visible = True
Next i

End Sub

Note: You may need to change Me to the name of the userform if the procedure is to be used outside of the userforms code module.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your suggesting. Anyway later I need to create a loop like: im1.Picture = LoadPicture(dir1) im2.Picture = LoadPicture(dir2) im3.Picture = LoadPicture(dir3) im4.Picture = LoadPicture(dir4) im5.Picture = LoadPicture(dir5) im6.Picture = LoadPicture(dir6) So I need also loop (dir & i)
Update your question with the full question. The answer I provided addresses what you asked but if you require more, you'll need to update it.
Sorry, I tought that there were an answer for both of my problems, I have updated
1

I quite like this syntax:

Private Sub CommandButton1_Click()
    Dim cCont As Control

    For Each cCont In Me.Controls
        If TypeName(cCont) = "Image" And VBA.Left$(cCont.Name, 3) = "imm" Then
           cCont.Visible = True
           cCont.Picture = LoadPicture("c:\..\pi" & VBA.Right$(cCont.Name, Len(cCont.Name) - 3) & ".jpg")
        End If
    Next cCont
End Sub

2 Comments

I was going to take this approach in my answer but from the code posted, the code is targeting specific images (prefixed with imm) rather than every image in the userform
I've updated it to get imm prefixes only and load the relevant picture.

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.