add multiple custom properties with a userform

E

Eric F.

I need to add multiple custom properties to a many documents in multiple
folders. The folders, property names, and values will vary so I want to have
some flexibility to change these values easily, say with a userform, rather
than hard code these. I haven't set up the folder picker part of the code yet
but think I will be OK there as I have several examples from here and the
Word MVP site and have already written some code similar to what I think I
will need.

My immediate problem is setting up code for a userform to enter the custom
document property names and values in textboxes. The basic code for a simple
userform with 1 textbox for the property name and a second for the property
value is something like this:

If CustPropName1.Text <> "" Then
With oDoc.CustomDocumentProperties
.Add Name:=CustPropName1.Text, _
LinkToContent:=False, _
Type:=msoPropertyTypeString, _
Value:=CustPropVal1.Text
End With
End If

I know I can repeat this code for as many pairs of text boxes as I want. It
seems I should be able to use a loop to handle any number of pairs; but I
can't make anything work. Any suggestions? Thanks.
 
J

Jay Freedman

The trick is to create a string by appending a number to the end of the
"base name" of a control (e.g., "CustPropName" & 1 becomes "CustPropName1")
and use that string as the index into the collection Me.Controls. The number
that you append is the loop index.

This works for three pairs of textboxes; to use more pairs, just add (and
properly name) the textboxes, and set the value of maxProps accordingly.

Private Sub btnOK_Click()
Const maxProps = 3
Dim oDoc As Document
Dim ctlName As Control
Dim ctlVal As Control
Dim idx As Integer

Set oDoc = ActiveDocument

For idx = 1 To maxProps
Set ctlName = Me.Controls("CustPropName" & idx)
Set ctlVal = Me.Controls("CustPropVal" & idx)

If ctlName.Text <> "" Then
With oDoc.CustomDocumentProperties
.Add Name:=ctlName.Text, _
LinkToContent:=False, _
Type:=msoPropertyTypeString, _
Value:=ctlVal.Text
End With
End If
Next idx

Me.Hide
End Sub

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 
E

Eric F.

Thanks Jay! In my fumbling around I didn't get all that close to the solution
but knew I had to build and increment a string to handle the text boxes.
Thanks for the help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top