+ Reply to Thread
Results 1 to 8 of 8

Exporting UserForm data to Word

Hybrid View

  1. #1
    Registered User
    Join Date
    09-22-2015
    Location
    Finland
    MS-Off Ver
    Office 2016
    Posts
    26

    Question Exporting UserForm data to Word

    Hey Excel Forum ppl!

    I've been reading your forum for a few weeks now and it has been very useful for me. I'm not very experienced with Excel + VBA but learning fast. (Only 1 month studies behind.. )

    I'm wondering if you guys could give me some advice since I came to a dead end with my project. I will try to explain my problem as clearly as possible:

    I'm working on a tool which picks up values (=text / ComboBox items) from a UserForm. The idea is that the typed text and chosen item from ComboBox are exported from Excel to existing Word document, and to certain points in it. The problem is that I can't figure out how to export the data from Excel to existing Word template. And of course I would also like to know how to export the data to certain points in the Word document

    Here's a simplified example attached:

    ExistingTemplate.docexcelforum1.xlsm

    Thank you in advance!

    -ODeveloper

  2. #2
    Forum Expert
    Join Date
    01-23-2013
    Location
    USA
    MS-Off Ver
    Microsoft 365 aka Office 365
    Posts
    3,863

    Re: Exporting UserForm data to Word

    Hi ODeveloper and welcome to ExcelForum,

    I made a few behind the scenes changes to your Userform:
    a. Changed Control Names
    b. Initialized the 'CommandButton' to 'Not Visible'
    c. Changed 'ComboBox' attributes to 'Match First Letter' and 'Match Required'.
    d. Changed 'Tab Order' so the 'Name' TextBox would have initial focus.

    Try the attached file which implements the following code.
    UserForm code:
    Option Explicit
    
    Private Sub TextBoxName_Change()
      'The Verify Routine Displays or Hides the 'Export' CommandButton
      Call VerifyUserFormDataIsReadyForExport
    End Sub
    
    Private Sub ComboBoxGender_Change()
      'The Verify Routine Displays or Hides the 'Export' CommandButton
      Call VerifyUserFormDataIsReadyForExport
    End Sub
    
    Private Sub CommandButtonExportDataToWord_Click()
    
      'Export Data From the UserForm to Word
      Call ExportUserFormDataToWord
      
      'Close the UserForm
      Unload Me
      
    End Sub
    
    Private Sub VerifyUserFormDataIsReadyForExport()
      'This Displays or Hides the 'Export' CommandButton
      'To Display the CommandButton all 'Export' Fields must contain data
    
      Dim sGender As String
      Dim sName As String
      
      Dim bReadyForExport As Boolean
    
      'Assume Data is Ready for Export
      bReadyForExport = True
    
      'Get the Values from the UserForm (removing leading/trailing spaces)
      sGender = Trim(UserForm1.ComboBoxGender.Value)
      sName = Trim(UserForm1.TextBoxName.Value)
      
      'If there is NO DATA, Not Ready for Export
      If Len(sGender) = 0 Then
        bReadyForExport = False
      End If
      
      'If there is NO DATA, Not Ready for Export
      If Len(sName) = 0 Then
        bReadyForExport = False
      End If
    
      'Display or Hide the 'Export' CommandButton
      If bReadyForExport = True Then
        CommandButtonExportDataToWord.Visible = True
      Else
        CommandButtonExportDataToWord.Visible = False
      End If
    
    End Sub
    Ordinary Module Code such as Module1 to ModExcelToWord:
    Option Explicit
    
    Sub DisplayUserForm1()
      UserForm1.Show
    End Sub
    
    Sub ExportUserFormDataToWord()
      'This Replaces Text in a Word Document with text from a UserForm
      '
      'Text in the Word Document is in the form of KEYWORDS preceeded by the '#' sign
      'e.g. The KEYWORD '#Name' (no apostrophes) is a KEYWORD
    
      'This is the name of the WORD file that will be accessed
      'The file MUST BE in the same folder as this file
      Const sWordFileNAME = "ExistingTemplate.doc"
    
      'Enumerated constants reference:
      'http://include.wutils.com/com-dll/constants/constants-Word.htm
      '
      'Word methods reference:
      'https://msdn.microsoft.com/en-us/library/office/ff822886.aspx
      '
      'The following CONSTANTS that start with 'wd' allow the use of 'Late Binding'
      'which does NOT require the inclusion of 'Microsoft Word xx.x Object Library' as a VBA REFERENCE
      Const wdCatalog = 3
      Const wdDefaultFirstRecord = 1
      Const wdDefaultLastRecord = -16
      Const wdDirectory = 3
      Const wdDoNotSaveChanges = 0
      Const wdSaveChanges As Long = -1
      Const wdPromptToSaveChanges As Long = -2
      Const wdEMail = 4
      Const wdEnvelopes = 2
      Const wdFax = 5
      Const wdFormLetters = 0
      Const wdMailingLabels = 1
      Const wdNotAMergeDocument = -1
      Const wdOpenFormatAuto = 0
      Const wdSendToNewDocument = 0
      
      Const wdMove = 0
      Const wdExtend = 1
      Const wdWord = 2
      Const wdSentence = 3
      Const wdStory = 6
      Const wdReplaceNone = 0
      Const wdReplaceOne = 1
      Const wdReplaceAll = 2
      
      
      Dim WordApp As Object
      Dim WordDoc As Object
      
      Dim sNewName As String
      Dim sNewGender As String
      Dim sPath As String
      Dim sPathAndWordFileName As String
    
      
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      'Initial Processing
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      
      'Get the Current Path of the file running the code
      sPath = ThisWorkbook.Path & "\"
      
      'Create the Path and Word File Combination
      sPathAndWordFileName = sPath & sWordFileNAME
    
      'Make sure the Word file exists
      If LJMFileExists(sPathAndWordFileName) = False Then
        MsgBox "Microsoft Word file DOES NOT EXIST." & vbCrLf & _
               "Folder: " & sPath & vbCrLf & _
               "File:       " & sWordFileNAME
        Exit Sub
      End If
      
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      'Get Replacement Values from the UserForm (remove leading/trailing spaces)
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      
      sNewGender = Trim(UserForm1.ComboBoxGender.Value)
      sNewName = Trim(UserForm1.TextBoxName.Value)
      
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      'Open the Word File Document
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      
      'Create Word application object
      Set WordApp = CreateObject("Word.Application")
      
      'Create Word Document Object and Open Word file
      'Make the word application visible
      'Set the focus on the Word document
      Set WordDoc = WordApp.documents.Open(sPathAndWordFileName)
      WordApp.Visible = True
      WordApp.Application.Activate
      
      'Open the Word File
      WordApp.documents.Open sPathAndWordFileName
        
      
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      'Replace Text in the Word Document
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
          
      'Replace Name
      With WordDoc.Application.Selection.Find
        .ClearFormatting
        .Text = "#Name"
        .Replacement.Text = sNewName
        .Execute Replace:=wdReplaceAll
      End With
      
      'Replace Gender
      With WordDoc.Application.Selection.Find
        .ClearFormatting
        .Text = "#Gender"
        .Replacement.Text = sNewGender
        .Execute Replace:=wdReplaceAll
      End With
      
      
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      'Termination
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
    
    ERROR_EXIT:
      'NOTE: The following code will not prompt the user to save changes in Excel 2003
      '      WordApp.Quit WILL prompt the user to save changes (if any)
      '
      'Save and Close the Word document
      'WordDoc.Saved = False
      'WordDoc.Save
      'WordDoc.Close SaveChanges:=wdDoNotSaveChanges
      'WordDoc.Close SaveChanges:=wdPromptToSaveChanges   'Close options: wdSaveChanges or wdPromptToSaveChanges
        
      'Close Microsoft Word
      'Word asks about what to do with the OUTPUT FILE
      WordApp.Quit
      
      'Clear object pointers
      Set WordApp = Nothing
      Set WordDoc = Nothing
    
    End Sub
    
    Private Function LJMFileExists(sPathAndFullFileName As String) As Boolean
      'This returns TRUE if a file exists and FALSE if a file does NOT exist
      
      Dim iError As Integer
      Dim iFileAttributes As Integer
    
      On Error Resume Next
      iFileAttributes = GetAttr(sPathAndFullFileName)
         
      'Check the internal error  return
      iError = Err.Number
      Select Case iError
        Case Is = 0
            iFileAttributes = iFileAttributes And vbDirectory
            If iFileAttributes = 0 Then
              LJMFileExists = True
            Else
              LJMFileExists = False
            End If
        Case Else
            LJMFileExists = False
      End Select
    
      On Error GoTo 0
    
    End Function
    It is a best practice to declare all variables. If you misspell a variable in your code, VBA will silently assume it is a Variant variable and go on executing with no clue to you that you have a bug. Go to the VBA development window, click Tools, Options, and check "Require Variable Declaration." This will insert the following line at the top of all new modules:
    Option Explicit
    This option requires all variables to be declared and will give a compiler error for undeclared variables.

    Lewis

  3. #3
    Registered User
    Join Date
    09-22-2015
    Location
    Finland
    MS-Off Ver
    Office 2016
    Posts
    26

    Re: Exporting UserForm data to Word

    Hey Lewis, and thanks for a quick answer!

    Your code works well! It just takes a little time for a newbie like me to chew that all Thanks for the comments within the code as well, makes it much easier to understand. Do you know if it's possible to add custom text through userform to Word documents header & footer? Let's say that I would like to have the #Name from textbox to header and footer, any solution?

    Thx in advance!

    -ODeveloper

  4. #4
    Forum Expert
    Join Date
    01-23-2013
    Location
    USA
    MS-Off Ver
    Microsoft 365 aka Office 365
    Posts
    3,863

    Re: Exporting UserForm data to Word

    I would like to have the #Name from textbox to header and footer, any solution?
    See the attached file. It attempts to replace each keyword in the:
    a. Main Body
    b. Header
    c. Footer

    I figured the general 'replace all' was better than replace some keywords in the 'Main Body', and/or some in the 'Header', and/or some in the 'Footer'. The code can be modified to do each section separately if that is what you want.

    I want to thank MacroPod in post #5 of the following link, for header/footer replacement code: http://www.msofficeforums.com/word-v...er-footer.html

    In an ordinary code module:
    Sub ExportUserFormDataToWord()
      'This Replaces Text in a Word Document with text from a UserForm
      '
      'Text in the Word Document is in the form of KEYWORDS preceeded by the '#' sign
      'e.g. The KEYWORD '#Name' (no apostrophes) is a KEYWORD
    
      'This is the name of the WORD file that will be accessed
      'The file MUST BE in the same folder as this file
      Const sWordFileNAME = "ExistingTemplate.doc"
      
      'Reference Post #5: http://www.msofficeforums.com/word-vba/22669-created-vba-find-replace-body-header-footer.html
      'Thank you MacroPod
      '
      '
      'Enumerated constants reference:
      'http://include.wutils.com/com-dll/constants/constants-Word.htm
      '
      'Word methods reference:
      'https://msdn.microsoft.com/en-us/library/office/ff822886.aspx
      '
      'The following CONSTANTS that start with 'wd' allow the use of 'Late Binding'
      'which does NOT require the inclusion of 'Microsoft Word xx.x Object Library' as a VBA REFERENCE
      Const wdCatalog = 3
      Const wdDefaultFirstRecord = 1
      Const wdDefaultLastRecord = -16
      Const wdDirectory = 3
      Const wdDoNotSaveChanges = 0
      Const wdSaveChanges As Long = -1
      Const wdPromptToSaveChanges As Long = -2
      Const wdEMail = 4
      Const wdEnvelopes = 2
      Const wdFax = 5
      Const wdFormLetters = 0
      Const wdMailingLabels = 1
      Const wdNotAMergeDocument = -1
      Const wdOpenFormatAuto = 0
      Const wdSendToNewDocument = 0
      
      Const wdMove = 0
      Const wdExtend = 1
      Const wdWord = 2
      Const wdSentence = 3
      Const wdStory = 6
      Const wdFindContinue = 1
      Const wdReplaceNone = 0
      Const wdReplaceOne = 1
      Const wdReplaceAll = 2
      
      
      Dim WordApp As Object
      Dim WordDoc As Object
      
      Dim sNewName As String
      Dim sNewGender As String
      Dim sPath As String
      Dim sPathAndWordFileName As String
    
      
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      'Initial Processing
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      
      'Get the Current Path of the file running the code
      sPath = ThisWorkbook.Path & "\"
      
      'Create the Path and Word File Combination
      sPathAndWordFileName = sPath & sWordFileNAME
    
      'Make sure the Word file exists
      If LJMFileExists(sPathAndWordFileName) = False Then
        MsgBox "Microsoft Word file DOES NOT EXIST." & vbCrLf & _
               "Folder: " & sPath & vbCrLf & _
               "File:       " & sWordFileNAME
        Exit Sub
      End If
      
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      'Get Replacement Values from the UserForm (remove leading/trailing spaces)
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      
      sNewGender = Trim(UserForm1.ComboBoxGender.Value)
      sNewName = Trim(UserForm1.TextBoxName.Value)
      
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      'Open the Word File Document
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      
      'Create Word application object
      Set WordApp = CreateObject("Word.Application")
      
      'Create Word Document Object and Open Word file
      'Make the word application visible
      'Set the focus on the Word document
      Set WordDoc = WordApp.documents.Open(sPathAndWordFileName)
      WordApp.Visible = True
      WordApp.Application.Activate
      
      'Open the Word File
      WordApp.documents.Open sPathAndWordFileName
        
      
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      'Replace Text in the Word Document:
      'a. Main Body
      'b. Header
      'c. Footer
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      
      Call ReplaceWordDocumentTextInMainBodyHeaderAndFooter(WordDoc, "#Name", sNewName)
      Call ReplaceWordDocumentTextInMainBodyHeaderAndFooter(WordDoc, "#Gender", sNewGender)
    
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
      'Termination
      ''''''''''''''''''''''''''''''''''''''''''''''''''''''
    
    ERROR_EXIT:
      'NOTE: The following code will not prompt the user to save changes in Excel 2003
      '      WordApp.Quit WILL prompt the user to save changes (if any)
      '
      'Save and Close the Word document
      'WordDoc.Saved = False
      'WordDoc.Save
      'WordDoc.Close SaveChanges:=wdDoNotSaveChanges
      'WordDoc.Close SaveChanges:=wdPromptToSaveChanges   'Close options: wdSaveChanges or wdPromptToSaveChanges
        
      'Close Microsoft Word
      'Word asks about what to do with the OUTPUT FILE
      WordApp.Quit
      
      'Clear object pointers
      Set WordApp = Nothing
      Set WordDoc = Nothing
    
    End Sub
    
    Sub ReplaceWordDocumentTextInMainBodyHeaderAndFooter(WordDoc As Object, sOriginalText As String, sReplacementText As String)
      'This replaces Text in a Word Document:
      'a. Main Body
      'b. Header
      'c. Footer
    
      Dim myWordSection As Object
      Dim myWordHeaderFooter As Object
    
      'Replace 'Main Body' Text
      Call ReplaceWordDocumentText(WordDoc.Range, sOriginalText, sReplacementText)
    
    
      'Replace 'Header' and 'Footer' Text
      For Each myWordSection In WordDoc.Sections
      
        'Replace 'Header' Text
        For Each myWordHeaderFooter In myWordSection.Headers
          Call ReplaceWordDocumentText(myWordHeaderFooter.Range, sOriginalText, sReplacementText)
        Next myWordHeaderFooter
          
        'Replace 'Footer' Text
        For Each myWordHeaderFooter In myWordSection.footers
          Call ReplaceWordDocumentText(myWordHeaderFooter.Range, sOriginalText, sReplacementText)
        Next myWordHeaderFooter
          
      Next myWordSection
    
    
    End Sub
    
    Sub ReplaceWordDocumentText(myWordRange As Object, sOriginalText As String, sReplacementText As String)
      'This replaces Word Document Text in a Given Range (usually a section) in a Word Document
      '
      'Reference Post #5: http://www.msofficeforums.com/word-vba/22669-created-vba-find-replace-body-header-footer.html
      'Thank you MacroPod
    
      'The following CONSTANTS that start with 'wd' allow the use of 'Late Binding'
      'which does NOT require the inclusion of 'Microsoft Word xx.x Object Library' as a VBA REFERENCE
      Const wdFindContinue = 1
      Const wdReplaceNone = 0
      Const wdReplaceOne = 1
      Const wdReplaceAll = 2
      
      'First search the main document using the Selection
      With myWordRange.Find
        .Text = sOriginalText
        .Replacement.Text = sReplacementText
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute Replace:=wdReplaceAll
      End With
    
    End Sub
    
    
    Private Function LJMFileExists(sPathAndFullFileName As String) As Boolean
      'This returns TRUE if a file exists and FALSE if a file does NOT exist
      
      Dim iError As Integer
      Dim iFileAttributes As Integer
    
      On Error Resume Next
      iFileAttributes = GetAttr(sPathAndFullFileName)
         
      'Check the internal error  return
      iError = Err.Number
      Select Case iError
        Case Is = 0
            iFileAttributes = iFileAttributes And vbDirectory
            If iFileAttributes = 0 Then
              LJMFileExists = True
            Else
              LJMFileExists = False
            End If
        Case Else
            LJMFileExists = False
      End Select
    
      On Error GoTo 0
    
    End Function
    Lewis

  5. #5
    Registered User
    Join Date
    09-22-2015
    Location
    Finland
    MS-Off Ver
    Office 2016
    Posts
    26

    Re: Exporting UserForm data to Word

    I finally got that all implented to my project, and it works very well so far!

    A thousand thanks to you Mr. Lewis, I couldn't have done it without your help!

    I might have further questions following, so lets keep this thread open, Thanks!

    BR,
    ODeveloper

  6. #6
    Registered User
    Join Date
    09-22-2015
    Location
    Finland
    MS-Off Ver
    Office 2016
    Posts
    26

    Re: Exporting UserForm data to Word

    Hi LJMetzger and others,

    This is and old topic, but maybe you could help me with an issue over here.

    According to these files and code:

    I have to make another userform which uses different template in the same workbook.

    1. Can I make another Module to this same workbook, and make this new userform only to use the another Module? I mean is it possible to make one userform to use only one module? If so, How can I "link" them together?

    2. Or is it possible to make a macro which changes the template what is going to be used?

    Thanks in advance!

  7. #7
    Forum Expert
    Join Date
    01-23-2013
    Location
    USA
    MS-Off Ver
    Microsoft 365 aka Office 365
    Posts
    3,863

    Re: Exporting UserForm data to Word

    1. Can I make another Module to this same workbook, and make this new userform only to use the another Module? I mean is it possible to make one userform to use only one module? If so, How can I "link" them together?

    2. Or is it possible to make a macro which changes the template what is going to be used?
    If I understand the question correctly, you are concerned about a UserForm using the wrong code.

    You should not have any problems if you follow and understand a few simple rules:
    a. All the bulit in UserForm routines are automatically Private. That means they can only be seen by that specific UsrForm.
    b. In general, my personal design guidelines are to make other routines inside the UserForm code module also Private. I try to have as little code inside the UserForm module as possible.
    c. I usually make routines in other modules 'Public' (accessible to anyone). To avoid a conflict between two Public routines, requires careful use of Routine Names.

    For example instead of a function called UserFormVerifyData(), if I would name the routine(s) UserForm1VerifyData(), UserForm2VerifyData() etc.

    I hope this helps.

    Lewis

  8. #8
    Registered User
    Join Date
    09-22-2015
    Location
    Finland
    MS-Off Ver
    Office 2016
    Posts
    26

    Re: Exporting UserForm data to Word

    I think you just answered my question!

    Thanks again Lewis!

    -ODeveloper

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Exporting a Userform Data to Excel
    By ssakthish in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 01-03-2013, 08:10 AM
  2. exporting data from a userform using listboxes
    By 2funny4words in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 05-09-2010, 11:52 PM
  3. exporting spreadsheet data to ms word!
    By miyat in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 12-10-2009, 05:13 AM
  4. exporting userform data to document
    By mania112 in forum Word Programming / VBA / Macros
    Replies: 8
    Last Post: 10-29-2009, 10:31 AM
  5. exporting data from excel into word
    By rwise in forum Excel General
    Replies: 2
    Last Post: 07-16-2008, 04:47 PM
  6. exporting data from excel into word
    By pboost1 in forum Excel General
    Replies: 16
    Last Post: 06-12-2008, 03:37 PM
  7. exporting data to Microsoft Word
    By Yarpsnesan in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 02-28-2008, 02:41 PM
  8. exporting Excel data to MS Word...
    By bl!zzarD in forum Excel General
    Replies: 1
    Last Post: 07-27-2007, 02:09 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1