Results 1 to 8 of 8

Exporting UserForm data to Word

Threaded View

  1. #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

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