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?

dax90
  • 1,088
  • 14
  • 29
  • Please use [FSO](http://stackoverflow.com/q/3233203/380384) to combine paths and filenames instead of `&`. More details [here](http://www.exceltrick.com/formulas_macros/filesystemobject-in-vba/) – John Alexiou Jul 16 '14 at 14:02

2 Answers2

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.

Gareth
  • 5,140
  • 5
  • 42
  • 73
  • 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) – dax90 Jul 16 '14 at 13:12
  • 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. – Gareth Jul 16 '14 at 13:15
  • Sorry, I tought that there were an answer for both of my problems, I have updated – dax90 Jul 16 '14 at 13:20
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
Alex P
  • 12,249
  • 5
  • 51
  • 70
  • 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 – Gareth Jul 16 '14 at 13:22
  • 1
    I've updated it to get `imm` prefixes only and load the relevant picture. – Alex P Jul 16 '14 at 15:58