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:
This option requires all variables to be declared and will give a compiler error for undeclared variables.
Lewis
Bookmarks