Copying a userform textbox text and pasting to a Word doc with a button click

chazrab

Well-known Member
Joined
Oct 21, 2006
Messages
917
Office Version
  1. 365
Platform
  1. Windows
Is this possible? The code I wrote below copies the text to the clipboard
easily enough. The last step is just pasting to a Word doc window on top excel.
Clipboard contents can always be pasted manually with Ctrl+V - I'd like to be able to convert Ctrl+V to code or
use other code to automate this.
Can anyone help with this. Code and images.

Code:
Private Sub cmdCOPY_Click()
ActiveWindow.WindowState = xlMinimized
Dim WordDoc As Object
Dim MyData As New DataObject
MyData.SetText TextBox1.Text
MyData.PutInClipboard
Set WordDoc = CreateObject("Word.Application")
WordDoc.Documents.Open "C:\Users\car19\OneDrive\Desktop\NOTES.docx"
WordDoc.Visible = True
End Sub

Thanks for anyone's help.
cr
 

Attachments

  • COPIES UF TEXTBOX TEXT, PASTES TO WORD DOC WINDOW DISPLAED ON TOP OF EXCEL AND SAVES.png
    COPIES UF TEXTBOX TEXT, PASTES TO WORD DOC WINDOW DISPLAED ON TOP OF EXCEL AND SAVES.png
    190.3 KB · Views: 23

Excel Facts

Using Function Arguments with nested formulas
If writing INDEX in Func. Arguments, type MATCH(. Use the mouse to click inside MATCH in the formula bar. Dialog switches to MATCH.
Hi, how about ....
VBA Code:
Private Sub cmdCOPY_Click()
    ActiveWindow.WindowState = xlMinimized
    
    Dim WordApp As Object
    Set WordApp = CreateObject("Word.Application")
    WordApp.Visible = True

    Dim TargetDoc As Object
    Set TargetDoc = WordApp.Documents.Open("C:\Users\car19\OneDrive\Desktop\NOTES.docx")
    WordApp.Selection.EndKey Unit:=6        ' 6=wdStory
    WordApp.Selection.TypeText Text:=TextBox1.Text
End Sub
 
Upvote 0
Hi, how about ....
VBA Code:
Private Sub cmdCOPY_Click()
    ActiveWindow.WindowState = xlMinimized
   
    Dim WordApp As Object
    Set WordApp = CreateObject("Word.Application")
    WordApp.Visible = True

    Dim TargetDoc As Object
    Set TargetDoc = WordApp.Documents.Open("C:\Users\car19\OneDrive\Desktop\NOTES.docx")
    WordApp.Selection.EndKey Unit:=6        ' 6=wdStory
    WordApp.Selection.TypeText Text:=TextBox1.Text
End Sub
Hi GWteB = thanks for helping. Images explain better than I can describe. Word doc window result should always stay on top of the
calling UF and user still be able to interact with both without one moving behind the other, if that's possible. Word does not have
that feature option that I could find, neither does anywhere on the web for a 64 bit machine. cr

cr
 

Attachments

  • FAIL MSG.png
    FAIL MSG.png
    56.5 KB · Views: 22
  • CODE LINE WHERE FAILS.png
    CODE LINE WHERE FAILS.png
    31.5 KB · Views: 18
Upvote 0
I see, well then I think it's best to keep your Excel UserForm in charge regarding opening and closing the required Word document.
Both your Excel UserForm and the Word document can stay visible on the computers desktop at the same time.
Note that the code prevents manually closing the Word document if the Excel UserForm is active at the same time.

To make this happen first set a reference in your VBA project to the Word Object Library. Be sure the desired project is active, then on the menu click Tools > References and search manually for the library. I'm on Office 2013 having Library version 15.0, you might have another version number, see attached.
After that, create a new Class module into your project: Menu > Insert > Class Module and press F4 to rename that module to CWordEventsSink.
See if this works for you.

ScreenShot098.png




This goes in the UserForm's module:
VBA Code:
Option Explicit

Private Type TLocals_UserForm
    WordApp         As Object
    WordDoc         As Object
    WordEvents      As CWordEventsSink
    IsDocAvailable  As Boolean
End Type
Private This As TLocals_UserForm

Private Const WORDDOCUMENT As String = "C:\Users\car19\OneDrive\Desktop\NOTES.docx"

Private Sub UserForm_Terminate()
    TerminateWordApp
End Sub

Private Sub cmdCOPY_Click()
    With This
        If Not .IsDocAvailable Then
            InitWordApp
        End If
        If .IsDocAvailable Then
            .WordApp.Selection.EndKey Unit:=wdStory
            .WordApp.Selection.TypeText Text:=Me.TextBox1.Text
        End If
    End With
End Sub

Private Sub InitWordApp()
    If VBA.CreateObject("Scripting.FileSystemObject").FileExists(WORDDOCUMENT) Then
        With This
            If Not IsFileOpen(WORDDOCUMENT) Then
                
                ' Word doc can be made available for opening and pasting, proceed
                Excel.Application.ActiveWindow.WindowState = xlNormal
                Set .WordApp = New Word.Application   
                Set .WordDoc = .WordApp.Documents.Open(WORDDOCUMENT)
                .WordApp.Visible = True
                .WordApp.ActiveWindow.WindowState = wdWindowStateNormal
                VBA.AppActivate .WordApp.Caption
                .IsDocAvailable = True
                Set .WordEvents = New CWordEventsSink
                .WordEvents.Initialize .WordApp, .WordDoc
            Else
                ' currently the Word Document is in use, disable copy button
                .IsDocAvailable = False
                MsgBox "Word Document is already open, please get it closed before you proceed!", vbExclamation, WORDDOCUMENT
            End If
        End With
    Else
        MsgBox "Word Document doesn't exist!", vbExclamation, WORDDOCUMENT
    End If
End Sub

Private Sub TerminateWordApp()
    With This
        If Not .WordEvents Is Nothing Then
            .WordEvents.Terminate argForceDocToClose:=False   ' << change argument to True if document needs to be closed
            Set .WordEvents = Nothing
            Set .WordDoc = Nothing
            Set .WordApp = Nothing
            .IsDocAvailable = False
        End If
    End With
End Sub

Private Function IsFileOpen(ByVal argFullName As String) As Boolean
    Dim FileNum As Long, ErrNum As Long
    FileNum = VBA.FreeFile()
    On Error Resume Next
    Open argFullName For Input Lock Read As #FileNum
    ErrNum = VBA.Err.Number
    Close FileNum
    IsFileOpen = VBA.CBool(ErrNum)
End Function


This goes in a Class module named CWordEventsSink:
VBA Code:
Option Explicit

Private WithEvents wdApp As Word.Application

Private Type TLocals_CWordEventsSink
    DocToWatch      As Word.Document
    CloseAllowed    As Boolean
End Type
Private This As TLocals_CWordEventsSink

Public Sub Initialize(ByVal argWdApp As Word.Application, ByVal argDoc As Word.Document)
    Set wdApp = argWdApp
    Set This.DocToWatch = argDoc
    This.CloseAllowed = False
End Sub

Public Sub Terminate(Optional ByVal argForceDocToClose As Boolean = False)
    Set wdApp = Nothing
    With This
        .DocToWatch.Save
        If argForceDocToClose Then
            .CloseAllowed = True
            .DocToWatch.Close
        End If
        Set .DocToWatch = Nothing
    End With
End Sub

Private Sub wdApp_DocumentBeforeClose(ByVal Doc As Word.Document, Cancel As Boolean)
    If VBA.StrComp(Doc.FullName, This.DocToWatch.FullName, vbTextCompare) = 0 Then
        If Not This.CloseAllowed Then
            Cancel = True
        End If
    End If
End Sub
 
Upvote 0
I see, well then I think it's best to keep your Excel UserForm in charge regarding opening and closing the required Word document.
Both your Excel UserForm and the Word document can stay visible on the computers desktop at the same time.
Note that the code prevents manually closing the Word document if the Excel UserForm is active at the same time.

To make this happen first set a reference in your VBA project to the Word Object Library. Be sure the desired project is active, then on the menu click Tools > References and search manually for the library. I'm on Office 2013 having Library version 15.0, you might have another version number, see attached.
After that, create a new Class module into your project: Menu > Insert > Class Module and press F4 to rename that module to CWordEventsSink.
See if this works for you.

View attachment 67326



This goes in the UserForm's module:
VBA Code:
Option Explicit

Private Type TLocals_UserForm
    WordApp         As Object
    WordDoc         As Object
    WordEvents      As CWordEventsSink
    IsDocAvailable  As Boolean
End Type
Private This As TLocals_UserForm

Private Const WORDDOCUMENT As String = "C:\Users\car19\OneDrive\Desktop\NOTES.docx"

Private Sub UserForm_Terminate()
    TerminateWordApp
End Sub

Private Sub cmdCOPY_Click()
    With This
        If Not .IsDocAvailable Then
            InitWordApp
        End If
        If .IsDocAvailable Then
            .WordApp.Selection.EndKey Unit:=wdStory
            .WordApp.Selection.TypeText Text:=Me.TextBox1.Text
        End If
    End With
End Sub

Private Sub InitWordApp()
    If VBA.CreateObject("Scripting.FileSystemObject").FileExists(WORDDOCUMENT) Then
        With This
            If Not IsFileOpen(WORDDOCUMENT) Then
               
                ' Word doc can be made available for opening and pasting, proceed
                Excel.Application.ActiveWindow.WindowState = xlNormal
                Set .WordApp = New Word.Application  
                Set .WordDoc = .WordApp.Documents.Open(WORDDOCUMENT)
                .WordApp.Visible = True
                .WordApp.ActiveWindow.WindowState = wdWindowStateNormal
                VBA.AppActivate .WordApp.Caption
                .IsDocAvailable = True
                Set .WordEvents = New CWordEventsSink
                .WordEvents.Initialize .WordApp, .WordDoc
            Else
                ' currently the Word Document is in use, disable copy button
                .IsDocAvailable = False
                MsgBox "Word Document is already open, please get it closed before you proceed!", vbExclamation, WORDDOCUMENT
            End If
        End With
    Else
        MsgBox "Word Document doesn't exist!", vbExclamation, WORDDOCUMENT
    End If
End Sub

Private Sub TerminateWordApp()
    With This
        If Not .WordEvents Is Nothing Then
            .WordEvents.Terminate argForceDocToClose:=False   ' << change argument to True if document needs to be closed
            Set .WordEvents = Nothing
            Set .WordDoc = Nothing
            Set .WordApp = Nothing
            .IsDocAvailable = False
        End If
    End With
End Sub

Private Function IsFileOpen(ByVal argFullName As String) As Boolean
    Dim FileNum As Long, ErrNum As Long
    FileNum = VBA.FreeFile()
    On Error Resume Next
    Open argFullName For Input Lock Read As #FileNum
    ErrNum = VBA.Err.Number
    Close FileNum
    IsFileOpen = VBA.CBool(ErrNum)
End Function


This goes in a Class module named CWordEventsSink:
VBA Code:
Option Explicit

Private WithEvents wdApp As Word.Application

Private Type TLocals_CWordEventsSink
    DocToWatch      As Word.Document
    CloseAllowed    As Boolean
End Type
Private This As TLocals_CWordEventsSink

Public Sub Initialize(ByVal argWdApp As Word.Application, ByVal argDoc As Word.Document)
    Set wdApp = argWdApp
    Set This.DocToWatch = argDoc
    This.CloseAllowed = False
End Sub

Public Sub Terminate(Optional ByVal argForceDocToClose As Boolean = False)
    Set wdApp = Nothing
    With This
        .DocToWatch.Save
        If argForceDocToClose Then
            .CloseAllowed = True
            .DocToWatch.Close
        End If
        Set .DocToWatch = Nothing
    End With
End Sub

Private Sub wdApp_DocumentBeforeClose(ByVal Doc As Word.Document, Cancel As Boolean)
    If VBA.StrComp(Doc.FullName, This.DocToWatch.FullName, vbTextCompare) = 0 Then
        If Not This.CloseAllowed Then
            Cancel = True
        End If
    End If
End Sub
Hi - Been away all day, just getting to this now. you spent time writing a lot of code here - thanks for that.
Give me time to study this a bit and test it. Will follow up. Thx again, cr
 
Upvote 0

Forum statistics

Threads
1,223,893
Messages
6,175,248
Members
452,623
Latest member
cliftonhandyman

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top