PDA

View Full Version : Refer Userform CommandButton name to module



Operon
01-21-2011, 02:27 AM
I am at the tail end of creating a Multipage Userform with 50 CommandButtons that will allow the user to add an image files to particular slides in a PPT presentation; i.e., CommandButton2, CommandButton3, CommandButton4, etc. The CommandButton's name is arithmetically related to the particular slide that will receive the image. The following code works perfectly. However, I would like to create a module so that I don't have to "hand code" each CommandButton. What is the preferred method to capture and pass the CommandButton name to the balance of the code in the presumptive module?

Many thanks in advance.

Cheers,

John

Sub CommandButton2_Click()

Dim cmdName As String
Dim dlgOpen As FileDialog
Dim PictFile As String
Dim pSlide As Long
Dim cmdNo As Long
Dim nLen As Long
Dim NoLen As Long
Dim rNo As Long

'Get name of CommandButton
cmdName = CommandButton2.Name
'MsgBox cmdName

'Parse CommandButton name
nLen = Len(cmdName)
NoLen = nLen - 13
rNo = Right$(cmdName, NoLen)

'Calculate slide number to insert image file
pSlide = rNo + 1
PictFile = ""

Set dlgOpen = Application.FileDialog(msoFileDialogFilePicker)

'Open file browser
With dlgOpen
If .Show = -1 Then
PictFile = .SelectedItems(1)
'MsgBox PictFile
End If
End With

Set dlgOpen = Nothing

'Insert file
If PictFile <> "" Then
With ActivePresentation.Slides(pSlide)
ActiveWindow.Selection.SlideRange.Shapes.AddPicture(FileName:=PictFile, LinkToFile:=msoFalse, SaveWithDocument:=msoTrue, Left:=30, Top:=250).Select
End With
End If
End Sub

Operon
01-22-2011, 12:46 AM
I was able to massage the code to work as a function module to be called from a CommandButton. Also, I used ActiveControl to retrieve the CommandButton's name. See working code below.

Function InsertPict()

Dim ctlCurrentControl As Control
Dim strControlName As String
Dim cmdName As String
Dim dlgOpen As FileDialog
Dim PictFile As String
Dim pSlide As Long
Dim cmdNo As Long
Dim nLen As Long
Dim NoLen As Long
Dim rNo As Long

'Get name of CommandButton
Set ctlCurrentControl = UserForm1.MultiPage1.SelectedItem.ActiveControl
cmdName = ctlCurrentControl.Name

'Parse CommandButton name
nLen = Len(cmdName)
NoLen = nLen - 13
rNo = Right$(cmdName, NoLen)

'Calculate slide number to insert image file
pSlide = rNo + 1
PictFile = ""

Set dlgOpen = Application.FileDialog(msoFileDialogFilePicker)

'Open file browser
With dlgOpen
If .Show = -1 Then
PictFile = .SelectedItems(1)
'MsgBox PictFile
End If
End With

Set dlgOpen = Nothing

'Insert file
If PictFile <> "" Then
ActiveWindow.View.GotoSlide pSlide
ActiveWindow.Selection.SlideRange.Shapes.AddPicture(FileName:=PictFile, LinkToFile:=msoFalse, SaveWithDocument:=msoTrue, Left:=30, Top:=250).Select
End If

End Function

Thanks for any intereted eyes.

Cheers,

John