View Single Post
 
Old 08-24-2020, 10:08 PM
Guessed's Avatar
Guessed Guessed is offline Windows 10 Office 2016
Expert
 
Join Date: Mar 2010
Location: Canberra/Melbourne Australia
Posts: 3,995
Guessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant future
Default

I usually try to modularise the code to make it easier to maintain the userforms and add/remove elements on the userform without having to update the code as well. The following code assumes you have populated the Tag property of each textbox on your userform and then you can use that tag value to find the relevant bookmark or content control that aligns with that textbox.
Code:
Private Sub CommandButton1_Click()
  Dim aCtrl As Control, sTag As String, strPath As String, aRng As Range
  For Each aCtrl In Me.Controls
    Select Case TypeName(aCtrl)
      Case "TextBox"
        sTag = aCtrl.Tag   'aCtrl.Name 'if you prefer
        If ActiveDocument.Bookmarks.Exists(sTag) Then
          Set aRng = ActiveDocument.Bookmarks(sTag).Range
          aRng.Text = aCtrl
          ActiveDocument.Bookmarks.Add Name:=sTag, Range:=aRng
        ElseIf ActiveDocument.SelectContentControlsByTitle(sTag).Count > 0 Then
          ActiveDocument.SelectContentControlsByTitle(sTag)(1).Range.Text = aCtrl
        End If
    End Select
  Next aCtrl
  strPath = Environ("USERPROFILE") & "\Documents\"
  ActiveDocument.SaveAs strPath & Me.TextBox2 & Me.TextBox1 & ".docx"
  Me.Hide
End Sub
__________________
Andrew Lockton
Chrysalis Design, Melbourne Australia
Reply With Quote